PHP Script to extract only bundle products from a json file and put them to another file

I am new in PHP and I am trying to get a specific data from a json file. Here`s the file:
{
“24-WG085”: {
“sku”: “24-WG085”,
“product_type”: “simple”,
“name”: “Sprite Yoga Strap 6 foot”,
“price”: 2.25
},
“24-WG085-dynamic”: {
“sku”: “24-WG085-dynamic”,
“product_type”: “simple”,
“name”: “Sprite Yoga Strap Dynamic”,
“price”: 10.45
},
“24-WG086”: {
“sku”: “24-WG086”,
“product_type”: “simple”,
“name”: “Sprite Yoga Strap 8 foot”,
“price”: 5.3
},
“24-WG087”: {
“sku”: “24-WG087”,
“product_type”: “simple”,
“name”: “Sprite Yoga Strap 10 foot”,
“price”: 8.35
},
“24-WG085_Group”: {
“sku”: “24-WG085_Group”,
“product_type”: “bundle”,
“name”: “Set of Sprite Yoga Straps”,
“price”: 11.4
},
“24-WG085-bundle-dynamic”: {
“sku”: “24-WG085-bundle-dynamic”,
“product_type”: “bundle”,
“name”: “Sprite Yoga Strap Dynamic Bundle”,
“price”: 14.45
},
“24-WG085-bundle-fixed”: {
“sku”: “24-WG085-bundle-fixed”,
“product_type”: “simple”,
“name”: “Sprite Yoga Strap Fixed Bundle”,
“price”: 17.5
}
}

So the idea if the product type is a ,bundle" to get the key- for example: Sprite Yoga Strap Dynamic Bundle. Here is my code so far:

  <?php
  $data = file_get_contents ("php-files-task.json");
    $json = json_decode($data, true);
    foreach ($json as $key => $value) {
        if (!is_array($value)) {
            echo $key . '=>' . $value . '<br/>';
        } else {
            foreach ($value as $key => $val) {
                echo $key . '=>' . $val . '<br/>';
            }
        }
    }
    $fp = fopen('results.json', 'w');

foreach ($value as $value) {
fputcsv($fp, $value);
}

fclose($fp);
 ?>

After I get all bundle products I want to put them in a new file- ,results.json". I will appreciate any help. Thanks!

When you have a set of data that you are operating on all in the same way, rather than to write a bunch of code with explicate loops, use php array functions, in this case use array_filter() to keep only the data you want -

$in_file = 'php-files-task.json';
$out_file = 'results.json';

// read the data and decode it
$data = json_decode(file_get_contents($in_file),true);

// examine the input data and any error
echo '<pre>';
print_r($data);
echo json_last_error_msg();

// define a search term
$search = ['key'=>'product_type', 'value'=>'bundle'];

// use array_filter() with a call-back function to keep only the data matching the search term
$data = array_filter(
		$data,
		function ($arr) use ($search) {
			return isset($arr[$search['key']]) && $arr[$search['key']] == $search['value'];
		}
	);
	
// examine the result
print_r($data);

// encode the result and save to a file
file_put_contents($out_file,json_encode($data,JSON_PRETTY_PRINT));
1 Like

Thank you for your help!

Sponsor our Newsletter | Privacy Policy | Terms of Service