49

I have an array of arrays like so:

array( array(), array(), array(), array() );

the arrays inside the main array contain 4 keys and their values. The keys are the same among all arrays like this:

array( 'id' => 'post_1',
       'desc' => 'Description 1',
       'type' => 'type1',
       'title' => 'Title'
     );

array( 'id' => 'post_2',
       'desc' => 'Description 2',
       'type' => 'type2',
       'title' => 'Title'
     );

So I want to create another array and extract the id and type values and put them in a new array like this:

array( 'post_1' => 'type1', 'post_2' => 'type2'); // and so on

The keys in this array will be the value of id key old arrays and their value will be the value of the type key.

So is it possible to achieve this? I tried searching php.net Array Functions but I don't know which function to use?

0

3 Answers 3

133

PHP 5.5 introduced an array function that does exactly what you want. I'm answering this in hopes that it may help someone in future with this question.

The function that does this is array_column. To get what you wanted you would write:

array_column($oldArray, 'type', 'id');

To use it on lower versions of PHP either use the accepted answer or take a look at how this function was implemented in PHP and use this library: https://github.com/ramsey/array_column

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

2 Comments

Additionally, you can wrap that in array_unique to filter out dupliate values :) php.net/manual/en/function.array-unique.php
This should be the selected answer.
34

Just use a good ol' loop:

$newArray = array();
foreach ($oldArray as $entry) {
    $newArray[$entry['id']] = $entry['type'];
}

2 Comments

I upvoted the question and the answer. How can I downvote PHP for not providing a better method?
@Olivier'Ölbaum'Scherler Good news: php has provided a function for this -- see the higher upvoted answer.
0

An alternative to @deceze's simple loop, for those poor folks still on a <5.5 version of PHP (like me), and not needing the excellent full implementation from Ramsey above, you could also use this:

$new_array = array_map(function ($elem) {
    return $elem['your_key'];
}, $old_array);

3 Comments

This answer does not populate the keys as required in the asked question. This answer is the <5.5 equivalent of array_column($old_array, 'your_key'), but array_map() cannot custom assign keys in its returned array.
You are of course correct @mickmackusa. I was so focused on my own problem, which was to get only values, that I posted before reading the question carefully. Rookie mistake.
You have the power to self-delete this answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.