Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP multidimensional array to simple array [duplicate]

Tags:

arrays

php

Which method is best practice to turn a multidimensional array

Array ( [0] => Array ( [id] => 11 ) [1] => Array ( [id] => 14 ) )

into a simple array? edit: "flattened" array (thanks arxanas for the right word)

Array ( [0] => 11 [1] => 14 )

I saw some examples but is there an easier way besides foreach loops, implode, or big functions? Surely there must a php function that handles this. Or not..?

like image 819
CyberJunkie Avatar asked May 13 '26 22:05

CyberJunkie


1 Answers

$array = array();
$newArray = array();

foreach ( $array as $key => $val )
{
    $temp = array_values($val);
    $newArray[] = $temp[0];
}

See it here in action: http://viper-7.com/sWfSbD


Here you have it in function form:

function array_flatten ( $array )
{
    $out = array();

    foreach ( $array as $key => $val )
    {
        $temp = array_values($val);
        $out[] = $temp[0];
    }

    return $out;
}

See it here in action: http://viper-7.com/psvYNO

like image 113
Joseph Silber Avatar answered May 19 '26 04:05

Joseph Silber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!