So I have a multidimensional array like the one below:
[0]=>
array(4) {
["id"] => 110
["list"] => {}
["MainProduct"] => 2 <- Step2: Replace the 2 with a 5 where productName is Oranges
["productName"] => Oranges <- Step1: Find where we have "Oranges"
}
[1]=>
array(4) {
["id"] => 111
["list"] => {}
["MainProduct"] => 110
["productName"] => Apples
}
Ultimately, what I need to achieve is to find were the value
for key
productName equals Oranges
and based on that to replace the value
for key
MainProduct in the same sub array.
I thought I should first find the index for the array containing Oranges
and then replace the value
for key
mainProduct but can’t seem to do it properly.
They key
names are always the same, while the value
names are different.
Also, the array is dynamic so the array with Oranges
won’t always have the same index.
This is the desired result:
[0]=>
array(4) {
["id"] => 110
["list"] => {}
["MainProduct"] => 5 <- This is changed to 5 where productName is "Oranges"
["productName"] => Oranges
}
[1]=>
array(4) {
["id"] => 111
["list"] => {}
["MainProduct"] => 110
["productName"] => Apples
}
2
Answers
A slight variant of the strategy you proposed:
The output is:
If you get the keys and combine with the
productName
values, then you can search it and get the key. Then use the key to updateMainProduct
:If
productName
is unique, then I would just modify the array to index on that: