带有两个数组和if条件求值的Foreach循环,用于查找匹配值PHP并更新值[重复]

5jvtdoz2  于 2022-12-28  发布在  PHP
关注(0)|答案(1)|浏览(67)
    • 此问题在此处已有答案**:

How to modify an array's values by a foreach loop?(2个答案)
昨天关闭。

Array1
(
    [0] => Array
        (
            [date] => 2022-12-01
            [result] => 0  
        )

    [1] => Array
        (
            [date] => 2022-12-02
            [result] => 0
        )

    [2] => Array
        (
            [date] => 2022-12-03
            [result] => 0
        )
                .
                .
                .
                .

    [31] => Array
        (
            [date] => 2022-12-31
            [result] => 0
        )

)


Array2
(
    [0] => Array
        (
            [date] => 2022-12-01
            [result] => 45
        )

    [1] => Array
        (
            [date] => 2022-12-03
            [result] => 15
        )
                .
                .
                .
                .

    [25] => Array
        (
            [date] => 2022-12-31
            [result] => 25
        )

)

Array3
(
    [0] => Array
        (
            [date] => 2022-12-01
            [result] => 45
        )

    [1] => Array
        (
            [date] => 2022-12-02
            [result] => 0
        )

    [2] => Array
        (
            [date] => 2022-12-03
            [result] => 15
        )
                .
                .
                .
                .

    [31] => Array
        (
            [date] => 2022-12-31
            [result] => 25
        )

)

我想把Array1和Array2合并成Array3。数组1包含所有空值月份的日期,而Array2只包含有值的日期。所以,我想循环两个数组,如果日期在Array2中,则使用Array2的值,否则使用Array1的0值。我尝试使用for每个循环,但Array!中的结果没有做任何更改。下面是我的代码:

foreach($Array1 as $arr1){
       foreach($Array2 as $arr2){
                if($arr1['date'] == $arr2['date']){
                    $arr1['date'] = $arr2['date'];
                    $arr1['result'] = $arr2['result'];
                }
       }
}
z9smfwbn

z9smfwbn1#

你需要将$arr1作为一个引用变量,这样赋值给它就可以修改数组,否则你修改的是数组的一个副本,当循环结束时,所做的修改就会丢失。

foreach($Array1 as &$arr1){

也不需要$arr1['date'] = $arr2['date'];,因为if条件意味着它们相同。

相关问题