简体   繁体   中英

How to merge array with same key into single array with all the key

I want to merge array with the same name and show all the same name in a single array.

I have array show below

Array
(
    [0] => Array
        (
            [location_name] => NTPL Vault
        )

    [1] => Array
        (
            [location_name] => NTPL Safe Room
        )

    [2] => Array
        (
            [location_name] => Safe NTPL
        )

)




$array = call_user_func_array('array_merge', $myArray);

I am expecting output as below...

[
  {
    "location_name": "NTPL"
  },
  {
    "location_name": "NJKL"
  },
  {
    "location_name": "KLDF"
  }
]

Your desired output is in JSON format, for which there are two commonly used functions in PHP:

For changing arrays from PHP forms to JSON, you might use json_encode and vice versa:

$array = array
    (
    '0' => array
    (
        'location_name' => 'NTPL Vault',
    ),

    '1' => array
    (
        'location_name' => 'NTPL Safe Room',
    ),

    '2' => array
    (
        'location_name' => 'Safe NTPL',
    ),

);

$output = json_encode($array);
var_dump($output);

Output:

string(97) "[{"location_name":"NTPL Vault"},{"location_name":"NTPL Safe Room"},{"location_name":"Safe NTPL"}]"

If you wish to change the values of location_name , you might simply use other functions.

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