PHP Multidimensional array flattening

113 views Asked by At

I have the following input array, I would like to flatten the array to evaluate true or false conditions.

array (
'all' => 
   array (
      '0' => 
         array (
            0 => 'true')
      '1' => 
         array (
            0 => 'true')    
      '2' => 
          array (
            0 => 'true')
         ),
  array (
       'any' => 
            array (
                '0' => 
                    array (
                        0 => 'true')
                '1' => 
                    array (
                            0 => 'false')   
))  

)

I would like to get the output in the following format.

Output Array:

all =>(
    true,
    true,
    true,
    any => (true,
           false)
)   
1

There are 1 answers

1
Amit Gupta On

There are many PHP built in functions available to sort out your issue.

You can use array_values like below:

$result = array_values($array, 'type');

And if you're using PHP 5.5+, you can use array_column() like below:

$result = array_column($array, 'type');

You can also try array_flatten or array_map for lower PHP versions.

Example with array_values:

<?php

$aNonFlat = array(
    1,
    2,
    array(
        3,
        4,
        5,
        array(
            6,
            7
        ),
        8,
        9,
    ),
    10,
    11
);

$objTmp = (object) array('aFlat' => array());

array_walk_recursive($aNonFlat, create_function('&$v, $k, &$t', '$t->aFlat[] = $v;'), $objTmp);

var_dump($objTmp->aFlat);

/*
array(11) {
  [0]=> int(1)
  [1]=> int(2)
  [2]=> int(3)
  [3]=> int(4)
  [4]=> int(5)
  [5]=> int(6)
  [6]=> int(7)
  [7]=> int(8)
  [8]=> int(9)
  [9]=> int(10)
  [10]=> int(11)
}
*/

?>