CyberJunkie
CyberJunkie

Reputation: 22674

PHP multidimensional array to simple array

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..?

Upvotes: 3

Views: 521

Answers (4)

Layke
Layke

Reputation: 53126

Here's an example. (It's probably not as "elegant" as xdazz", but it's an alternate without using "use" closure.) This is how the array might start out like:

Start

array (size=2)
  0 => 
    array (size=1)
      'woeid' => string '56413072' (length=8)
  1 => 
    array (size=1)
      'woeid' => string '56412936' (length=8)      

Then you might want to have something like this:

Target

   array (size=2)
      0 => string '56413072' (length=8)
      1 => string '56412936' (length=8)

You can use array_walk_recursive

Code

$woeid = array();
array_walk_recursive($result['results']['Result'], function ($item, $key, $woeid) {
     if ($key == 'woeid') {                                       
           $woeid[] = $item;
     }
}, &$woeid);

Upvotes: 0

xdazz
xdazz

Reputation: 160833

You could use array_walk_recursive to flatten an array.

$ret = array(); 
array_walk_recursive($arr, function($var) use (&$ret) { 
  $ret[] = $var; 
}); 
var_dump($ret); 

Upvotes: 2

Joseph Silber
Joseph Silber

Reputation: 219920

$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

Upvotes: 3

Jared Drake
Jared Drake

Reputation: 1002

If you have a multidimensional array that shouldn't be a multidimensional array (has the same keys and values) and it has multiple depths of dimension, you can just use recursion to loop through it and append each item to a new array. Just be sure not to get a headache with it :)

Upvotes: 1

Related Questions