Tuesday 4 September 2018

Trying to remove all values ​​from a multidimensional array (recursive)

I am trying to create a single array that contains all of the values of an existing multidimensional array. This is what I have so far:

function MaxArray($arr) {

    foreach ($arr as $value) {

        if (is_array($value)) {
            MaxArray($value);
        } else {
            $array[] = $value;
        }
    }
    print_r($array);

}

$arr = array(array(141,151,161), 2, 3, array(101, 202, array(303,404, array(1,2))));

MaxArray($arr);

When I execute this code, I get this response from the print_r function...
Array ( [0] => 141 [1] => 151 [2] => 161 ) Array ( [0] => 1 [1] => 2 ) Array ( [0] => 303 [1] => 404 ) Array ( [0] => 101 [1] => 202 ) Array ( [0] => 2 [1] => 3 )

As you can see, this is not what I am looking for and I can't figure out how to combine all of the values in the multidimensional array into a single array. Can anyone please point me in the right direction here?

What you're trying to do is often called 'array flattening', so ArrayFlatten is probably a better name for a function than MaxArray (since the latter sounds like it'll return the highest value in the array, which max does very well). ArrayFlatten could be written like this:
function ArrayFlatten($array, $return) {
  for ($x = 0; $x < count($array); $x++) {
    if(is_array($array[$x])) {
      $return = ArrayFlatten($array[$x], $return);
    }
    else {
      if($array[$x]) {
        $return[] = $array[$x];
      }
    }
  }

  return $return;
}

And used like this:
$myarray = array('a','b',array(array(array('x'),'y','z')),array(array('p')));
$res = ArrayFlatten($myarray,array());

To get this:
Array
(
    [0] => a
    [1] => b
    [2] => x
    [3] => y
    [4] => z
    [5] => p
)
From here.

0 comments:

Post a Comment