简体   繁体   English

如何在PHP中访问数组项的兄弟

[英]How can I access an array item's sibling in PHP

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 现在我的值'item2'='value2'来自其他地方

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' 我试图找到一种方法,仅用一行代码来访问数组中'item2'='value2'的所有项目并修改'item4'的值

I could easily do something like this if I knew that I needed to change it for array[1] only: 如果知道只需要将其更改为array [1],就可以轻松地执行以下操作:

$array[1]['item4'] = 'new value';

But I need to update the value only for the items where 'item2' is equal to 'value2' 但是我只需要为“ item2”等于“ 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? 当jQuery符合特定条件时,它们可以轻松找到兄弟姐妹,也许我不知道PHP中有类似的东西吗?

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... 我希望没有其他人需要阅读您的代码...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM