Reputation:
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);
?>
Upvotes: 1
Views: 503
Reputation: 985
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);
Upvotes: 0
Reputation: 72289
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
Upvotes: 2
Reputation: 1043
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.
Upvotes: 1