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

问题描述 投票:0回答:2

我有这样的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数组中的index加1与photoList数组中的id相同,它将在photoList数组中更新alt,其值为alt array by index plus

我试着这样:

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

alt仍然是空的。它没有更新

我希望结果如下:

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

我该怎么做?

php arrays indexing
2个回答
1
投票

更好的方法是这样做:

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

这种方式你只使用一个循环。另外,原始循环的错误在于您将值分配给循环内的临时变量。这不会影响您循环的阵列。

编辑:

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


2
投票

你必须使用变量($ value1)by reference

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

如果没有它你使用子项$value1的'内部副本',所以$photoList不会更新。

© www.soinside.com 2019 - 2024. All rights reserved.