繁体   English   中英

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

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

我有这样的alt数组:

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

我有这样的photoList数组:

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

我要检查一个状况

如果alt数组中的索引加1与photoList数组中的id相同,则它将通过index加1将alt数组的值更新到photoList数组中的alt

我这样尝试:

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

然后我检查:

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

替代项仍然为空。 它不会更新

我希望这样的结果:

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'
    )
);

我该怎么做?

您必须通过引用使用vars($ value1):

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

$photoList ,您将使用子项目$value1的“内部副本”,因此$photoList不会得到更新。

更好的方法是这样做:

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

这样一来,您仅使用一个循环。 另外,原始循环的问题在于您正在将值分配给循环内的临时变量。 这不会影响正在循环的阵列。

编辑

我只是发现您根本不需要关心$photoList[$key]['id'] 在此示例中这是无关紧要的,因为两个数组中元素的顺序相同。

暂无
暂无

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

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