Your data looks like JSON, so you'll need to convert it to a PHP array first:
$products = json_decode($data, true);
Now you can iterate like this:
$product_array = array();
foreach ($products as $product) {
$product_array[] = array(
"title" => $product["title"], // product title
"barcode" => $product["variants"][0]["barcode"], // product barcode
"sku" => $product["variants"][0]["sku"] // product SKU
);
}
Notice the added [0]
in the foreach
loop, as well as the $product_array
array (because you were overwriting the $products
array in the loop itself). The [0]
is to get the first element of the array variants
, as there can be more. You could add another foreach
loop to iterate them all.
Also note that you already have a complete array after using json_decode
. You can check that by just running:
var_dump(json_decode($data, true));
Where $data
contains the JSON data you mentioned.
Updated answer with loop inside loop:
$product_array = array();
foreach ($products as $product) {
// I'm using the name $item, if I used $product it would overwrite the variable in the loop
$item = array(
"title" => $product["title"], // product title
"variants" => array() // for now an empty array, we will fill it in the next step
);
// now we fill the empty arrays inside the array above, by iterating all variants
foreach($product["variants"] as $variant) {
$item["variants"][] = array(
"barcode" => $variant["barcode"], // product barcode
"sku" => $variant["sku"] // product SKU
);
}
$product_array[] = $item; // now we add the item with all the variants to the array with all the products
}
var_dump($product_array); // show the results