0

im currently struggling with converting this array in PHP to a more simplified one. This is my array to start with stored in $array:

   [0] => Array
       (
           [name] => name-1
           [value] => xXX
       )

   [1] => Array
       (
           [name] => name-2
           [value] => YYY
       )

I would like to transfrom this array to this simplified one $array_new:

   [0] => Array
       (
           [name-1] => xXX
       )

   [1] => Array
       (
           [name-2] => YYY
       )

I sadly don't know were to start... Could somebody help me out?

Edit: After I converted the array via array_column() oder foreach loop I still cant get the right data with $array_new['name-2'];

Sigron
  • 3
  • 3

3 Answers3

4

You can use array-column to do that. The documentation said:

array_column ( array $input , mixed $column_key [, mixed $index_key = NULL ] ) : array

So do:

$first_names = array_column($array, 'value', 'name');

Live example: 3v4l

dWinder
  • 11,597
  • 3
  • 24
  • 39
  • This transforms the array, but when I try to get the second name I will end up with the first name... echo $first_names['name-1']; = xXX echo $first_names['name-2']; = xXX – Sigron Sep 18 '19 at 09:04
  • @Sigron - don't know why but added to my example and it works: https://3v4l.org/pKFJo – dWinder Sep 18 '19 at 09:13
  • Not sure but the question says the output should be `[0] => Array ( [name-1] => xXX )` which has an extra level compared to this output `Array( [name-1] => xxx`. – Nigel Ren Sep 18 '19 at 09:17
0

Question

Alright, this is a question I see a lot of beginners deal with. Just be a little creative:

Answer

//Let's get your old array:
$old = [
   0 => [
      'name' => 'name-1',
      'value' => 'xXX'
   ],
   1 => [
      'name' => 'name-2',
      'value' => 'YYY'
   ]
];

//Let's create an array where we will store the new data:
$result = [];

foreach($old as $new) { //Loop through
   $result[$new['name']] = $new['value']; //Store associatively with value as value
}

var_dump($result);

Result:

Array[2] => [
   [name-1] => xXX,
   [name-2] => YYY
];
Community
  • 1
  • 1
Thrallix
  • 699
  • 5
  • 20
0

Using a foreach:

<?php

$items =
[
    [
        'plant' => 'fern',
        'colour' => 'green'
    ],
    [
        'plant' => 'juniper',
        'colour' => 'blue'
    ]
];

foreach($items as $item) {
    $output[][$item['plant']]=$item['colour'];
}
var_dump($output);

Output:

array(2) {
    [0]=>
    array(1) {
    ["fern"]=>
    string(5) "green"
    }
    [1]=>
    array(1) {
    ["juniper"]=>
    string(4) "blue"
    }
}
Progrock
  • 7,373
  • 1
  • 19
  • 25