简体   繁体   中英

How to merge two arrays in php?

I have the following arrays which I'd like to combine / merge to create a single array that I can loop through to add images and their respective titles to a database.

Array 1:

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

Array 2:

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

Here's the format of the array I'd like to create.

Merged Arrays:

[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"
}

If I understand you correctly this called zip , not merge . You can do this with array_map() function:

$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);

Here is demo .

array_merge()是将其用作array_map()的回调的方式:

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

Will the structure of the arrays be the same? And will the size of those arrays also always be the same? If not, there is no sure way to do this, if yes, you can do a simple loop:

$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);

This should work :

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM