1

I have some problems with parent array that contains multiple children array. It will be necessary that the array children, does not contain themselves other children array, but if it is the case, then to raise these array grandchildren at the level of children.

[0] => Array (
    [0] => Array (
        [name] => ...
        [count] => ...
        [url] => ...
        [html] => ...
    )
    [1] => Array (
        [name] => ...
        [count] => ...
        [url] => ...
    )
    [2] => Array (
        [1] => Array (
            [name] => ...
            [count] => ...
            [url] => ...
            [html] => ...
        )
        [2] => Array (
            [name] => ...
            [count] => ...
            [url] => ...
        )
    )
    [3] => Array (
        [name] => ...
        [count] => ...
        [url] => ...
    )
    [4] => Array (
        [name] => ...
        [count] => ...
        [url] => ...
    )
);

In the example array["2"] contain 2 array, I want that the 2 array go up one level and so become brothers and not children.

Can you help me please with the right function ?

function transformMultipleArraysTo1(array $multipleArrays = null)
{
    $newArray = array();
    if (!isArrayEmpty($multipleArrays)) {
        foreach ($multipleArrays as $array) {
            if (is_array($array)) {
                foreach ($array as $singleArray) {
                    if (is_array($singleArray)) {
                        $newArray[] = $singleArray;
                    } else {
                        continue 2;
                    }
                }
                $newArray[] = $array;
            }
        }
    }
    return $newArray;
}

Many thanks

1 Answers1

3

I came up with this solution, not the prettiest, but it works.

function RemoveThoseNastyGrandchildren(array $array = NULL){
  foreach ($array as $ckey => $child) {
    foreach($child as $gckey => $grandchild){
      if(is_array($grandchild)){
        $array[] = $grandchild;
        array_splice($array[$ckey],$gckey);
      }
    }
  }
  $length = count($array);
  for($i = 0; $i < $length ; $i++){
    if(!empty($array[$i][0]) && is_array($array[$i][0])){
      array_splice($array,$i,1);
      $i = -1;
      $length = count($array);
    }
  }
  //print("<pre>".print_r($array,true)."</pre>"); <---- To print it pretty uncomment
  return $array;
}

The First Loop:

will iterate through all relatives, looking for the potential grandchildren. If it finds one of these nasty grandchildren it'll append it to their parents, becoming a grandchildren again.


After that we just have to disensamble the former grandchildrens bodies, and that's what ...


The Second Loop does:

It's iterating through the changed array, looking for empty bodies. Then return the freshly shaped array familytree and whooosh, you got rid of those GCs.

D.Schaller
  • 611
  • 3
  • 19