合并两个不等的二维数组

时间:2015-11-09 16:35:29

标签: php

我有两个数组:

$addresses = array(array('address' => 'Address1', 'housenumber' => 22, 'zipcode' => '1234 AB', 'city' => 'Amsterdam', 'country' => 'Netherlands'),
                   array('address' => 'Address2', 'housenumber' => 62, 'zipcode' => '1234 AC', 'city' => 'Rotterdam', 'country' => 'Netherlands'),
                   array('address' => 'Address3', 'housenumber' => 63, 'zipcode' => '1234 AD', 'city' => 'Eindhoven', 'country' => 'Netherlands'));

$tasks = array(array('task_action' => 'pick up', 'note' => 'Some note 1'),
               array('task_action' => 'deliver', 'note' => 'Some note 2'),
               array('task_action' => 'pick up', 'note' => 'Some note 3'));

这就是我想要实现的目标:

$NewArray = array(array('address' => 'Address 1', 'housenumber' => 22, 'zipcode' => '1234 AB', 'city' => 'Amsterdam', 'country' => 'Nederland', 'task_action' => 'pick up', 'note' => 'Some note'),
                  array('address' => 'Address 2', 'housenumber' => 62, 'zipcode' => '1234 AC', 'city' => 'Rotterdam', 'country' => 'Nederland', 'task_action' => 'deliver', 'note' => 'Some note 2'),
                  array('address' => 'Address 3', 'housenumber' => 63, 'zipcode' => '1234 AD', 'city' => 'Eindhoven', 'country' => 'Nederland', 'task_action' => 'pick up', 'note' => 'Some note 3'));

我尝试过这样的事情:

for ($x = 0; $x < count($addresses); $x++) {
    for ($x = 0; $x < count($tasks); $x++) {
        $addresses[$x][] = $tasks[$x];
    }
}

有人能为我提供一点帮助吗?

2 个答案:

答案 0 :(得分:1)

您可以将其视为多维数组,但实际上它是一个条目列表。

您有一个地址列表和一个任务列表,您想要将它们组合在一起:

foreach ($addresses as $index => $_) {
    $addresses[$index] = array_merge($addresses[$index], $tasks[$index]);
}

答案 1 :(得分:1)

你可以试试这个:

$address = array(array('address' => 'Address1', 'housenumber' => 22, 'zipcode' => '1234 AB', 'city' => 'Amsterdam', 'country' => 'Netherlands'),
                 array('address' => 'Address2', 'housenumber' => 62, 'zipcode' => '1234 AC', 'city' => 'Rotterdam', 'country' => 'Netherlands'),
                 array('address' => 'Address3', 'housenumber' => 63, 'zipcode' => '1234 AD', 'city' => 'Eindhoven', 'country' => 'Netherlands'));

$tasks = array(array('task_action' => 'pick up', 'note' => 'Some note 1'),
               array('task_action' => 'deliver', 'note' => 'Some note 2'),
               array('task_action' => 'pick up', 'note' => 'Some note 3'));

$i = 0;
foreach ($addresses as $key => $value) {
    $NewArray[] = $value + $tasks[$i];
    $i++;
}

var_dump($NewArray);