1

I have this array...

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

And I am extracting the names like this...

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

Which gives me...

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

My question is how can I modify it so that I get this...

Array
(
    [RESULT84] => RESULT84
    [RESULT2] => RESULT2
    [RESULT1] => RESULT1
)

Is something like array_fill_keys my best bet?

3
  • array_combine. Though it sounds off that you need keys and values with the same string... Commented Jun 20, 2016 at 9:38
  • $names[array_column($data['finals'], 'name')] = array_column($data['finals'], 'name'); maybe Commented Jun 20, 2016 at 9:40
  • Possible duplicate of How to use array values as keys without loops? Commented Jun 20, 2016 at 9:53

2 Answers 2

7

Pass third parameter name into array_column to make it key

 $names = array_column($data['finals'], 'name','name');
 print_r($names);
Sign up to request clarification or add additional context in comments.

Comments

2

Saty answered it right. Here is the complete code:

<?php
$data = Array
    (
        'result' => 'Success',
        'finals' => Array
        (
            Array
                (
                    'id' => 633,
                    'name' => 'RESULT84'
                ),
            Array
                (
                    'id' => 766,
                    'name' => 'RESULT2'
                ),
            Array
                (
                    'id' => 22,
                    'name' => 'RESULT1'
                )
        )
    );

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.