There has been a few other questions regarding replacing values in multidimensional array on here, but I didn’t find anything regarding what I was trying to do, exactly, per se.
I have an array that I get from an API and I need to update a few values based on other values in the array tree before sending the API payload to the browser.
In the array when the sale[0] === true
I am looking for some logic to then replace the [price][0]
value with a corresponding new sale price.
Using the foreach
, I can easily loop through the each of the nodes in the array, but I am unsure once I loop through the array, how I can update the original array with new price if/when sale node === true.
Array ( [response] => Array ( [0] => Array ( [results] => Array ( [0] => Array ( [items] => Array ( [0] => Array ( [id] => Array ( [0] => 846471605959 ) [title] => Array ( [0] => Test Item 846471605959 ) [imageURL] => Array ( [0] => https://foo/bar/images/846471605959.jpg ) [itemURL] => Array ( [0] => https://foo/bar/item/846471605959 ) [price] => Array ( [0] => 799.00 ) [sale] => Array ( [0] => true ) ) [1] => Array ( [id] => Array ( [0] => 414953260545 ) [title] => Array ( [0] => Test Item 414953260545 ) [imageURL] => Array ( [0] => https://foo/bar/images/414953260545.jpg ) [itemURL] => Array ( [0] => https://foo/bar/item/414953260545 ) [price] => Array ( [0] => 199.00 ) [sale] => Array ( [0] => false ) ) [2] => Array ( [id] => Array ( [0] => 684865199812 ) [title] => Array ( [0] => Test Item 684865199812 ) [imageURL] => Array ( [0] => https://foo/bar/images/684865199812.jpg ) [itemURL] => Array ( [0] => https://foo/bar/item/684865199812 ) [price] => Array ( [0] => 699.00 ) [sale] => Array ( [0] => false ) ) [3] => Array ( [id] => Array ( [0] => 987800965761 ) [title] => Array ( [0] => Test Item 987800965761 ) [imageURL] => Array ( [0] => https://foo/bar/images/987800965761.jpg ) [itemURL] => Array ( [0] => https://foo/bar/item/987800965761 ) [price] => Array ( [0] => 499.00 ) [sale] => Array ( [0] => true ) ) [4] => Array ( [id] => Array ( [0] => 005457536677 ) [title] => Array ( [0] => Test Item 005457536677 ) [imageURL] => Array ( [0] => https://foo/bar/images/005457536677.jpg ) [itemURL] => Array ( [0] => https://foo/bar/item/005457536677 ) [price] => Array ( [0] => 99.00 ) [sale] => Array ( [0] => false ) ) ) ) ) } ) )
Advertisement
Answer
Use a reference variable for the foreach
iteration variable, then you can update the element in place.
foreach $data['response'][0]['results'][0]['items'] as &$item) { if ($item['sale'][0]) { $item['price'][0] = $new_price; } }
If you also need to loop through all the elements in the sale
array, add a nested loop.
foreach $data['response'][0]['results'][0]['items'] as &$item) { foreach ($item['sale'] as $i => $sale) { if ($sale) { $item['price'][$i] = $new_price; } } }