1

I have an array that looks like this....

Array
(
    [result] => Success
    [finals] => Array
        (
            [0] => Array
                (
                    [id] => 633
                    [name] => RESULT84
                )
                [0] => Array
                (
                    [id] => 766
                    [name] => RESULT2
                )
                [0] => Array
                (
                    [id] => 22
                    [name] => RESULT1
                )
        )
)

Using PHP, I am trying to create another array from it that only contains the [name] field.

Do I need to create a new array from this or is there a way to use it as is?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278

1 Answers1

1

With array_columm(), assuming your array is in a variable called $data:

$names = array_column($data['finals'], 'name');

print_r($names);

Yields:

Array
(
    [0] => RESULT84
    [1] => RESULT2
    [2] => RESULT1
)

array_column() is available from PHP version 5.5.0.

You may also use array_map():

$names = array_map(function ($final) {
    return $final['name'];
}, $data['finals']);

Hope this helps :)

Darragh Enright
  • 13,676
  • 7
  • 41
  • 48
  • If you need the name in a signle array you can declare a new array `$array =[];` and the use the array_push global function within a foreach and do `array_push($array, $value['name']);` – Nico Orfi Jun 19 '16 at 21:20