0

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"
  }
]
Saveen
  • 4,120
  • 14
  • 38
  • 41

1 Answers1

1

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.

Emma
  • 27,428
  • 11
  • 44
  • 69