简体   繁体   中英

Merge 2 associative arrays in PHP

I have 2 arrays, so first is:

{
    "title_heading_1": "Name",
    "last_name": "Trenkle",
    "first_name": "Jason",
    "middle_name": "Jason",
}

And the second one is:

{
    "Title Heading 1": "",
    "Last Name": "",
    "First Name": "",
    "Middle Name": "",
}

The question is how am i going to merge those 2 arrays where the key of the first array will be replaced by the key of the second array. So the result will be like this:

{
    "Title Heading 1": "Name",
    "Last Name": "Trenkle",
    "First Name": "Jason",
    "Middle Name": "Jason",
}

How would i do that on PHP. I tried foreach but still didn't get the right output.

If the keys and values match and are guaranteed to be in order, you can very easily do:

$result = array_combine(array_keys($second), array_values($first));
//array_values is probably not necessary

If the keys of the first and/or second array could be in any order but are consistently named as above, this should do the trick:

foreach ($first as $key => $value) {
   $second[ucwords(str_replace('_', ' ', $key))] = $value;
}

Oh and use json_decode to decode the strings into PHP arrays if you don't already know to do this.

$array1 = (array) json_decode('{
    "title_heading_1": "Name",
    "last_name": "Trenkle",
    "first_name": "Jason",
    "middle_name": "Jason",
}');

$array2 = (array) json_decode('{
    "Title Heading 1": "",
    "Last Name": "",
    "First Name": "",
    "Middle Name": "",
}');

$result = array_merge($array1, $array2);
print_r($result);

Use array_combine . First parameter is for the keys, the second is for the values. eg

<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

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