1

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);```
2
  • Have you tried anything? Commented Oct 13, 2021 at 9:10
  • Yes, Iam, i try with call_user_func_array , array_walk_recursive, array_column... Commented Oct 13, 2021 at 9:24

3 Answers 3

1

Oneliner is:

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

Fiddle here.

Sign up to request clarification or add additional context in comments.

Comments

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

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

print_r($b);

Result:

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

6 Comments

this is on of the source how i got it, source is JSON and i if use json_decode this not works: [ { "value": "0 800 nnn nnnn" }, { "value": "00 800-nnnnnnnn" }, { "value": "National (720)" }, { "value": "Vienna" } ]
you can $array = json_decode($json, true); to convert it into array. the true is required.
and second option 3v4l.org/daJsf
missing }after {"city":"New York"
|
0

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

2 Comments

It will be just [Berlin. London ...] with numeric keys. Probably array_column($array, 'city', 'city'); might do the job.
@u_mulder you are absolutely right

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.