如何在php中合并两个数组?

时间:2016-05-19 14:53:30

标签: php arrays

我有以下数组,我想组合/合并创建一个单独的数组,我可以循环将图像及其各自的标题添加到数据库。

数组1:

[0] => array(1) {
  ["filename"] => string(22) "1463668615_1_image.jpg"
}
[1] => array(1) {
  ["filename"] => string(22) "1463668641_1_image.jpg"
}

数组2:

[0] => array(1) {
  ["title"] => string(15) "My image title"
}
[1] => array(1) {
  ["title"] => string(5) "Title"
}

这是我想要创建的数组的格式。

合并数组:

[0] => array(2) {
  ["filename"] => string(22) "1463668615_1_image.jpg",
  ["title"] => string(3) "My image title"
}
[1] => array(2) {
  ["filename"] => string(22) "1463668641_1_image.jpg",
  ["title"] => string(0) "Title"
}

4 个答案:

答案 0 :(得分:2)

如果我理解正确,这称为 zip ,而不是合并。您可以使用array_map()函数执行此操作:

$filenames = [
    ['filename' => '1463668615_1_image.jpg'],
    ['filename' => '1463668641_1_image.jpg']
];

$titles = [
    ['title' => 'Title1'],
    ['title' => 'Title2']
];

$zipped = array_map(function ($elem1, $elem2) {
    return [
        'filename' => $elem1['filename'],
        'title' => $elem2['title']
    ];
}, $filenames, $titles);

var_dump($zipped);

这是demo

答案 1 :(得分:2)

array_merge()就是在array_map()中使用它作为回调的方式:

$result = array_map('array_merge', $array1, $array2);

答案 2 :(得分:1)

阵列的结构是否相同?这些阵列的大小也总是一样吗?如果没有,没有确定的方法可以做到这一点,如果是的话,你可以做一个简单的循环:

$arr1 = array(
    0 => array(
        "filename" => "1463668615_1_image.jpg",
    ),
    1 => array(
        "filename" => "1463668641_1_image.jpg",
    ),
);

$arr2 = array(
    0 => array(
        "title" => "My image title",
    ),
    1 => array(
        "title" => "Title",
    ),
);

$new = array();
for ($k = 0, $size = count($arr1); $k < $size; $k++) {
    $new[$k]['filename'] = $arr1[$k]['filename'];
    $new[$k]['title'] = $arr2[$k]['title'];
}

var_dump($new);

答案 3 :(得分:0)

这应该有效:

<强> PHP

    $filenames = [["filename" => "1463668615_1_image.jpg"], ["filename" => "146366865213_image.jpg"]];
    $titles = [["title" => "Titre1"], ["title" => "Titre22"]];

    foreach ($filenames as $key => &$value) {
         $value['title'] = $titles[$key]['title'];
    }

    var_dump($filenames);