kkis
kkis

Reputation: 49

PHP normalize multidimensional array

want to normalize an array and need help.

Array i have:

$myArr = array(
  array(
    array(
      array("id" => 1)
    )
  ),
  array("id" => 2),
  array("id" => 3),
  array(
    array(
     "id" => 4)
    )
);

Array i want to have:

 $myArr = array(
  array("id" => 1),
  array("id" => 2),
  array("id" => 3),
  array("id" => 4)
);

My idea to solve that prob is calling a recursive method, which is not working yet:

function myRecArrFunc(&myarr){
  $output = [];

  foreach{$myarr as $v}{
      if(!isset{$v["id"]){
       $output[] = myRecArrFunc($v);
      } else{
        $output[] = $v;
      }
  }      

  return $output
}

Currently the output of the function is the same as the input. Someone has an idea what have to be done?

Upvotes: 3

Views: 872

Answers (1)

trincot
trincot

Reputation: 350310

Yould use RecursiveIteratorIterator:

$result = [];
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($myArr)) as $k => $v) {
    $result[] = [$k => $v];
}

Or even simpler, array_walk_recursive:

$result = [];
array_walk_recursive($myArr, function($v, $k) use (&$result) {
    $result[] = [$k => $v];
});

About your code

Your code had at least 5 syntax errors, but ignoring those, you need to take into account that the recursive call will return an array, with potentially many id/value pairs. So you need to concatenate that array to your current results. You can use array_merge to make the code work:

function myRecArrFunc(&$myarr){
    $output = [];

    foreach($myarr as $v){
        if(!isset($v["id"])){
            $output = array_merge($output, myRecArrFunc($v));
        } else{
            $output[] = $v;
        }
    }      
    return $output;
}

Upvotes: 4

Related Questions