Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP normalize multidimensional array

Tags:

php

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?

like image 930
kkis Avatar asked Dec 08 '25 06:12

kkis


1 Answers

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;
}
like image 90
trincot Avatar answered Dec 09 '25 20:12

trincot