1

Here i am having one multidimensional array , using this array i have to merge the single array, i have tried in my point of view i have to use three foreach loop and then i have to push on one array,but my concern is if i am using foreach loop means my performance it will reduce,any one update my code with out for each loop or simplfied code

My Array



 Array
(
    "100" => Array
        (
            "class 1" => Array
                (
                    "0" => "ABC"
                    "1" => "CDE"
                )

            "class 2" => Array
                (
                    "0" => "F"
                )
        )

    "200" => Array
        (
            "class 3" => Array
                (
                    "0" => "G"
                )
        )

      )

Expected Output

 Array
(
 "0" => "100"
 "1" => "ABC"
 "2" => "CDE"
 "3" => "F"
 "4" => "200"
 "5" => "G"
)

I had tried like below

    <?php
$array = Array
(
    "100" => Array
        (
            "class 1" => Array
                (
                    "0" => "ABC",
                    "1" => "CDE"
                ),

            "class 2" => Array
                (
                    "0" => "F"
                )
        ),

    "200" => Array
        (
            "class 3" => Array
                (
                    "0" => "G"
                )
        )

      );
foreach($array as $firstKey => $firstVal){
    $mainArray[] = $firstKey;
    foreach($firstVal as $secondKey => $secondVal){
        foreach($secondVal as $thiredKey => $thiredVal){
             $mainArray[] = $thiredVal;
        }
    }

}
echo "<pre>";
print_r($mainArray);

?>
5
  • Please show us the code you've tried. Also, using foreach isn't automatically bad. It's pretty fast, unless you're iterating through a lot using it. Commented Sep 19, 2018 at 5:22
  • You want to "flaten" the array, you will find lots of examples for that on google. Commented Sep 19, 2018 at 5:23
  • @ Magnus Eriksson, please check i had updated what i tried Commented Sep 19, 2018 at 5:35
  • You still haven't told us why you don't want to use foreach, though. Commented Sep 19, 2018 at 5:39
  • @Prasanna you can achieve this without foreach; refer my answer below. Commented Sep 19, 2018 at 5:52

3 Answers 3

2

With foreach():

$final_array = array();

foreach($array as $key=>$arr){ // apply foreach on initial array

    $final_array[] = $key; // assign key first

    foreach($arr as $ar){ // now child is also array so iterate over it

        $values = array_values($ar); // get all values of child array

        foreach($values as $val){ // iterate over child array values

            $final_array[] = $val; //assign them one-by-one

        }

    }

}

print_r($final_array);// print final array

Output:- https://eval.in/1058692

Without foreach():

$result = array();
array_walk($original_array, function($item,$key) use (&$result){
   $result[] = $key;
   array_walk_recursive($item, function($v) use (&$result){ 
     $result[] = $v; 
   });
});
print_r($result );

Output:- https://3v4l.org/ECgdu

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

4 Comments

@Prasanna - Why this anti-foreach? Using foreach is even faster than using some array_*-functions in certain situations.
In my opinion, foreach would be your most quickest solution and will absolutely not affect your performance unless you have a lot, and I mean a LOT of iterations.
@Lachie agreed with you. But i added other way too.(Just for OP's sake, i always prefer foreach())
@AlivetoDie Yep great answer. @Prasanna - if you did a benchmark test between the two you'll find that foreach() is actually much faster as well.
1

You can flatten the multidimensional array like this

$result = array();
array_walk_recursive($original_array, function($v) use (&$result){ 
   $result[] = $v; 
});

As you can see, your array will be processed into the closure/anonymous function and will flatten it as an end result.

3 Comments

I tried your code, but i am not getting my expected output
Please check my expected output from top
Of course, the indexes needs to be handled some other way. @Prasanna show me your code in this case. What have you done so far?
0

You can achieve this without using foreach() or for() loop by using array_walk() and array_walk_recursive().

Here is the code;

// Your input array
$input = array (
    100 => array(
        "class 1" => array("ABC", "CDE"),
        "class 2" => array("F")
    ),
    200 => array(
        "class 3" => array("G")
    )
);

$result = array();
array_walk($input, function($val, $key) use (&$result){
    $result[] = $key;
    array_walk_recursive($val, function($v, $k) use (&$result){
        $result[] = $v;
    });
});
// Your result
echo "<pre>";
print_r($result);

Comments

Your Answer

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