简体   繁体   English

如何通过php中的条件更新数组中的值?

[英]How can I update value in the array by a condition on the php?

I have alt array like this : 我有这样的alt数组:

$alt = array('chelsea', 'mu', 'arsenal');

I have photoList array like this : 我有这样的photoList数组:

$photoList = array(
    array(
        'id'    => 1,
        'name'  => 'chelsea.jpg',
        'alt'   => ''
    ),
    array(
        'id'    => 2,
        'name'  => 'mu.jpg',
        'alt'   => ''
    ),
    array(
        'id'    => 3,
        'name'  => 'arsenal.jpg',
        'alt'   => ''
    )
);

I want to check a condition 我要检查一个状况

If index plus 1 in the alt array same with id in the photoList array, it will update alt in the photoList array with value of alt array by index plus 1 如果alt数组中的索引加1与photoList数组中的id相同,则它将通过index加1将alt数组的值更新到photoList数组中的alt

I try like this : 我这样尝试:

foreach($photoList as $key1 => $value1) {
    foreach ($alt as $key2 => $value2) {
        if($value1['id'] == $key2+1)
            $value1['alt'] = $value2;
    }
}

Then I check with : 然后我检查:

echo '<pre>';print_r($photoList);echo '</pre>';

The alt is still empty. 替代项仍然为空。 It does not update 它不会更新

I hope the result like this : 我希望这样的结果:

photoList = array(
    array(
        'id'    => 1,
        'name'  => 'chelsea.jpg',
        'alt'   => 'chelsea'
    ),
    array(
        'id'    => 2,
        'name'  => 'mu.jpg',
        'alt'   => 'mu'
    ),
    array(
        'id'    => 3,
        'name'  => 'arsenal.jpg',
        'alt'   => 'arsenal'
    )
);

How can I do it? 我该怎么做?

You have to use the vars ($value1) by reference : 您必须通过引用使用vars($ value1):

                           // THIS & is the trick
foreach($photoList as $key1 => &$value1) {
    foreach ($alt as $key2 => $value2) {
        if($value1['id'] == $key2+1)
            $value1['alt'] = $value2;
    }
}

Without that you work with an 'internal copy' of the sub-item $value1 , so $photoList doesn't get updated. $photoList ,您将使用子项目$value1的“内部副本”,因此$photoList不会得到更新。

A better approach will be to do that: 更好的方法是这样做:

foreach($photoList as $key => $value)
    $photoList[$key]['alt'] = $alt[$key];

This way round you use only one loop. 这样一来,您仅使用一个循环。 Also, what's wrong with your original loop is that you are assigning the value to the temporary variable inside the loop. 另外,原始循环的问题在于您正在将值分配给循环内的临时变量。 This is not affecting the array you are looping over. 这不会影响正在循环的阵列。

EDIT : 编辑

I just figured out that you do not need to care about $photoList[$key]['id'] at all. 我只是发现您根本不需要关心$photoList[$key]['id'] It's irrelevant in this example as the order of the elements is the same in both arrays. 在此示例中这是无关紧要的,因为两个数组中元素的顺序相同。

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

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