Home > Software engineering >  Merging Arrays into one Array and populate keys with same values
Merging Arrays into one Array and populate keys with same values

Time:10-13

I need to merge Arrays into one Array and replace $key with $values of the same array.

My Array looks like this:

Array 
( 
  [0] => Array 
  ( 
  [city] => Berlin 
  ) 
  [1] => Array 
  ( 
  [city] => London
  ) 
  [2] => Array 
  ( 
  [city] => New York 
  )
  [3] => Array 
  ( 
  [city] => Vienna
  )
)

Desired result

Array 
( 
  [Berlin] => Berlin 
  [London] => London
  [New York] => New York 
  [Vienna] => Vienna
)

updates: source looks like this:

$a = json_decode('[{"city":"Berlin"},{"city":"London"},{"city":"New York"}, {"city":"Vienna"}]', true);```

CodePudding user response:

Oneliner is:

$newArray = array_column($yourArray, 'city', 'city');

Fiddle here.

CodePudding user response:

$a = [['city' => 'Berlin'], ['city' => 'London']];
$b = [];

foreach ($a as $arr) $b[$arr['city']] = $arr['city'];

print_r($b);

Result:

Array ( [Berlin] => Berlin [London] => London )

CodePudding user response:

You can use array_column :

$res = array_column($array, 'city');

this will give you your result, but as key you will have integer values, to get the city also as key, check @u_mulder answer

  • Related