0

I have a source array that looks like this:

$data = array(
    'foo' => array(
        'bar' => 'foo_bar',
        'baz' => 'foo_baz'
    ),
    'fizz' => array(
        'bar' => 'fizz_bar',
        'baz' => 'fizz_baz'
    )
);

I would like to create another array by selecting a key: bar or baz, which will return all of the root keys with the values of the specified key?

some_function($data, 'bar') == array(
    'foo' => 'foo_bar',
    'fizz' => 'fizz_bar'
);

Is there a built-in php function(s) to generate the following results without doing my own loops?

1 Answer 1

1
$data = array(
    'foo' => array(
        'bar' => 'foo_bar',
        'baz' => 'foo_baz'
    ),
    'fizz' => array(
        'bar' => 'fizz_bar',
        'baz' => 'fizz_baz'
    )
);

To select bar:

$result = array_combine(
    array_keys($data),
    array_column($data, 'bar')
);

Here's an example:

php > var_dump(array_combine(array_keys($data), array_column($data, 'bar')));
array(2) {
  ["foo"]=>
  string(7) "foo_bar"
  ["fizz"]=>
  string(8) "fizz_bar"
}

Note that array_column() was introduced in PHP 5.5.

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

1 Comment

I was writing the exact same answer, so if you don't mind, I just added the example I was going to show and the note about 5.5+. Rollback if you don't like :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.