Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: how to turn multidimensional array to single dimension dynamically

I have an array like that

array(4) {
  [0]=>
  array(2) {
    [0]=>
    string(10) "2012-05-23"
    [1]=>
    string(10) "2012-05-31"
  }
  [1]=>
  array(2) {
    [0]=>
    string(10) "2012-05-30"
    [1]=>
    string(10) "2012-06-07"
  }
  [2]=>
  array(2) {
    [0]=>
    string(10) "2012-06-02"
    [1]=>
    string(10) "2012-06-07"
    }
}

I want turn this array into

  array(6) {
    [0]=>
    string(10) "2012-05-23"
    [1]=>
    string(10) "2012-05-31"
    [2]=>
    string(10) "2012-05-30"
    [3]=>
    string(10) "2012-06-07"
    [4]=>
    string(10) "2012-06-02"
    [5]=>
    string(10) "2012-06-07"
    }

and I want to do it dynamically. I mean I could have an array here with 100 dimensions. So must be something in loop :)

like image 486
Ultima Enos Avatar asked Jul 04 '26 12:07

Ultima Enos


2 Answers

$final_array =array();
foreach ($data as $val)
 {
    foreach($val as $val2)
     {
        $final_array[] = $val2;
     }
 }
like image 124
Moyed Ansari Avatar answered Jul 06 '26 01:07

Moyed Ansari


function makeArray($finalArray,$element) {
 foreach ($element as $key => $value){
  if(is_array($value)) makeArray($finalArray,$value);
  else $finalArray[] = $value;
 }
}

If you want a "general-pourpose" solution, this is the one

Obviously you have to call it, the first time, with $finalArray as an empty Array and $element as your starting array

like image 39
DonCallisto Avatar answered Jul 06 '26 02:07

DonCallisto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!