PlanetHackers PlanetHackers - 4 months ago 9
PHP Question

How to extract multidimensional associative array to simple numeric array

Here is a code sample

Array
(
[0] => Array
(
[ID] => 1197
)
[1] => Array
(
[ID] => 1078
)
)


I want it to convert into simple index array as:

Array( 1197, 1078 )


I know it can be done by iterating each index and assigning into a temp array. I want a one liner syntax like
array_filter
do in many cases. Is there any built-in function in PHP which do my task in one line, any mix of statement in one line. I don't want to use it in loops.

Answer

If you are using PHP > 5.5.0, you can use array_column:

$ids = array_column($array, 'ID');

On the linked page, you'll find a substitute for older versions:

if(!function_exists("array_column"))
{

    function array_column($array,$column_name)
    {

        return array_map(function($element) use($column_name){return $element[$column_name];}, $array);

    }

}