如何在多个数组中查找和替换特定值

时间:2018-07-12 06:52:51

标签: php arrays

我想从数组中找到 flag 键并替换新值。例如,如果我发现标志值== 2,那么我将放置新值而不是旧值。

以下是我的数组。

Array
(
    [0] => Array
        (
            [id] => 863
            [flag] => 1
            [qty] => 2
            [size] => 8
            [fly_name] => Bead Headed Prince Nymphs size 18
        )

    [1] => Array
        (
            [id] => 861
            [flag] => 1
            [qty] => 2
            [size] => 8
            [fly_name] => Bead Headed Prince Nymphs size 14
        )

    [2] => Array
        (
            [id] => 671
            [flag] => 1
            [qty] => 4
            [size] => 8
            [fly_name] => Royal Wulff size 12
        )

    [3] => Array
        (
            [id] => 661
            [flag] => 1
            [qty] => 2
            [size] => 3
            [fly_name] => Hare's Ear Tan size 16
        )
)

我想查找flag key == 2,然后替换flag key的新值,我尝试按照以下方式进行操作,但不起作用。

if(in_array(2, $fliesUserColumn)) { // search value in the array
    foreach($fliesUserColumn as $key => $val)
    {
            if ($val == '2') $fliesUserColumn[$key] = 'search4';
            }
    }else{
            echo "not";
    }
        echo "<pre>";
        print_r ($flyOfStores);
        echo "</pre>";
    die;

与数组中的新值一样输出

Array
(
    [0] => Array
        (
            [id] => 863
            [flag] => newvalue
            [qty] => 2
            [size] => 8
            [fly_name] => Bead Headed Prince Nymphs size 18
        )

    [1] => Array
        (
            [id] => 861
            [flag] => newvalue
            [qty] => 2
            [size] => 8
            [fly_name] => Bead Headed Prince Nymphs size 14
        )
   ...

)

2 个答案:

答案 0 :(得分:2)

请尝试以下示例

foreach ($fliesUserColumn as $key => $val) {
        if ($fliesUserColumn[$key]['flag'] == '2') {
            $fliesUserColumn[$key]['flag'] = 'Newvalue';
       } 
}

答案 1 :(得分:1)

尝试一下

    foreach ($fliesUserColumn as $key => $val) {
        if ($fliesUserColumn[$key]['flag'] == '2') {
            $fliesUserColumn[$key] = 'search4';
        } else {
                echo "not";
        }
    }