3

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?

1
  • 1
    Your code has several syntax issues. A missing dollar before myarr, a loose brace, missing parentheses around function argument for isset, a missing semi-colon near the end.... Commented Dec 16, 2018 at 9:35

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.