Home » Php » php – How to extract specific array keys and values to another array?

php – How to extract specific array keys and values to another array?

Posted by: admin April 23, 2020 Leave a comment

Questions:

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?

How to&Answers:

Just use a good ol’ loop:

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

Answer:

PHP recently added new function to their array functions that does exactly what you wanted.
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');

Please note that it was only introduced in PHP 5.5.0 version, so to use it on lower versions of PHP either use accepted answer or take a look at how this function was implemented in PHP and use this library: https://github.com/ramsey/array_column