PHP:合并多维数组替换值

时间:2015-04-07 12:52:19

标签: php arrays multidimensional-array

我正在尝试根据day_id将以下两个数组合并在一起。如果第二个数组中的数据与数组1中的day_id相同,则替换它。

从当天开始的天数:

Array (
 [0] => Array (
    [day] => Tuesday
    [open] => 06:00:00
    [close] => 15:00:00
    [day_id] => 3
    )
 [1] => Array (
    [day] => Wednesday
    [open] => 06:00:00
    [close] => 15:00:00
    [day_id] => 4
    )
 [2] => Array (
    [day] => Thursday
    [open] => 06:00:00
    [close] => 15:00:00
    [day_id] => 5
    )
 [3] => Array (
    [day] => Friday
    [open] => 06:00:00
    [close] => 15:00:00
    [day_id] => 6
    )
 [4] => Array (
    [day] => Saturday
    [open] =>
    [close] =>
    [day_id] => 7
    )
 [5] => Array (
    [day] => Sunday
    [open] =>
    [close] =>
    [day_id] => 1
    )
 [6] => Array (
    [day] => Monday
    [open] => 06:00:00
    [close] => 15:00:00
    [day_id] => 2
    )
)

我想与之前的数组合并的数组数据。

Array (
 [0] => Array (
    [day] => Saturday
    [open] => 07:00:00
    [close] => 15:00:00
    [day_id] => 7
    )
 [1] => Array (
    [day] => Friday
    [open] => 07:00:00
    [close] => 15:00:00
    [day_id] => 6
    )
)

结果我想要:

 Array (
     [0] => Array (
        [day] => Tuesday
        [open] => 06:00:00
        [close] => 15:00:00
        [day_id] => 3
        )
     [1] => Array (
        [day] => Wednesday
        [open] => 06:00:00
        [close] => 15:00:00
        [day_id] => 4
        )
     [2] => Array (
        [day] => Thursday
        [open] => 06:00:00
        [close] => 15:00:00
        [day_id] => 5
        )
     [3] => Array (
        [day] => Friday
        [open] => 07:00:00
        [close] => 15:00:00
        [day_id] => 6
        )
     [4] => Array (
        [day] => Saturday
        [open] => 07:00:00
        [close] => 15:00:00
        [day_id] => 7
        )
     [5] => Array (
        [day] => Sunday
        [open] =>
        [close] =>
        [day_id] => 1
        )
     [6] => Array (
        [day] => Monday
        [open] => 06:00:00
        [close] => 15:00:00
        [day_id] => 2
        )
    )

我尝试过使用array_replace_recursive($storeArray, $overrideArray);,但只根据索引号进行合并。使用两个查询从数据库中提取所有数据。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

试试这个:

// $original = array with original values
// $override = array with values to override
// $combined = merge result
$combined = array_map(
    function($day) use ($override) {
        foreach ($override as $newDay) {
            if ($day['day_id'] == $newDay['day_id']) {
                return $newDay;
            }
        }
        return $day;
    }, $original
);

...或者直接修改$original

array_walk($original,
    function(&$day) use ($override) {
        foreach ($override as $newDay) {
            if ($day['day_id'] == $newDay['day_id']) {
                $day = $newDay;
            }
        }
    }
);