0

Don't know this question is asked before or not, cannot find after lot of searching.

My array looks like this,

array(3) {
  [0]=>
  array(2) {
    [0]=>
    array(1) {
      ["userId"]=>
      string(3) "421"
    }
    [1]=>
    array(1) {
      ["userId"]=>
      string(3) "329"
    }
  }
  [1]=>
  array(1) {
    [0]=>
    array(1) {
      ["userId"]=>
      string(3) "329"
    }
  }
  [4]=>
  array(2) {
    [0]=>
    array(1) {
      ["userId"]=>
      string(3) "329"
    }
    [1]=>
    array(1) {
      ["userId"]=>
      string(3) "421"
    }
  }
}

What I want is,

array(1) {
  [0]=>
  array(5) {
    [0]=>
    array(1) {
      ["userId"]=>
      string(3) "421"
    }
    [1]=>
    array(1) {
      ["userId"]=>
      string(3) "329"
    }
    [2]=>
    array(1) {
      ["userId"]=>
      string(3) "329"
    }
    [3]=>
    array(1) {
      ["userId"]=>
      string(3) "329"
    }
    [4]=>
    array(1) {
      ["userId"]=>
      string(3) "421"
    }
  }
}

I have tried with array_merge, array_combine and a lot of foreach() loops. But didn't get luck for desired output.

Don't know how to do this. Please help.

1 Answer 1

1

You can flatten your array like this:

$arr = array(array(['user' => 1], ['user' => 2]), ['user' => 3]);
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
foreach($iterator as $val) {
  $flattened_arr[0][] = $val;
}
var_dump($flattened_arr);

UPDATE: If you don't want to use RecursiveIteratorIterator, the you can also do it like this using array_walk_recursive():

$non_flat_arr = array(array(['user' => 1], ['user' => 2]), ['user' => 3]);
$objTmp = (object) array('flat_arr' => array());
array_walk_recursive($non_flat_arr, create_function('&$v, $k, &$t', '$t->flat_arr[] = $v;'), $objTmp);
var_dump([ 0 => $objTmp->flat_arr]);

This will give you the output as:

array:1 [
  0 => array:3 [
    0 => 1
    1 => 2
    2 => 3
  ]
]

Hope this helps!

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much. But what if RecursiveIteratorIterator do not supports on the live site server?(Do not know what professionally or technically 'live site server' called as).
@KeyurK - If you find this answer correct and helpful then accept & upvote this answer as it motivates me to give answers to other questions like this and helps others to quickly find the correct answer!
Yes will do. Surely.

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.