So I have an array that I dynamically generate and looks like this:
$array[1] = array(
'item1' => 'value1',
'item2' => 'value2',
'item3' => 'value3',
'item4' => 'value4',
'item5' => 'value5'
);
$array[2] = array(
'item1' => 'value100',
'item2' => 'value200',
'item3' => 'value300',
'item4' => 'value400',
'item5' => 'value500'
);
...
Now I have the value of 'item2' = 'value2'coming from somewhere else
I'm trying to find a way, with only one line of code, to access all the items in the array where 'item2' = 'value2' and modify the value of 'item4'
I could easily do something like this if I knew that I needed to change it for array[1] only:
$array[1]['item4'] = 'new value';
But I need to update the value only for the items where 'item2' is equal to 'value2'
I know I could loop thought it but I'm trying to find a way to do it with only one line of code. jQuery can easily find siblings when they match a certain criteria maybe there is something similar in PHP I'm not aware of?
Hope this helps
$array[1] = array(
'item1' => 'value1',
'item2' => 'value2',
'item3' => 'value3',
'item4' => 'value4',
'item5' => 'value5'
);
$array[2] = array(
'item1' => 'value100',
'item2' => 'value200',
'item3' => 'value300',
'item4' => 'value400',
'item5' => 'value500'
);
function test(&$item, $key){
if($item['item2'] == 'value2'){
$item['item4'] = 'new value';
}
}
array_walk($array, 'test');
its not very pretty but here:
foreach($array as &$child) { if($child['item2'] == 'value2') { $child['item4'] = 'new value'; }}
I hope no one else needs to read your code...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.