So I have something like this:
$C = [ $B = [ $S = [$D[]], $H = [$C[]], $G = [$L[]]]]
I need to put array $H (which I know the name), with all of it’s elements on the first place, so it goes like this:
$C = [ $B = [ $H = [$C[]], $S = [$D[]], $G = [$L[]]]]
How can I do that?
Advertisement
Answer
Hope this solution solves your purpose:
<?php $C = ['B' => ['S' => ['C' => []], 'H' => ['D' => []], 'G' => ['L' => []]]]; function moveArrayElementOnTop($array, $element = 'H') { $finalArray = array(); foreach ($array as $key => $values) { foreach ($values as $k => $v) { if ($k == $element) { $temp[$key][$k] = $v; unset($array[$key][$k]); } } if (isset($temp[$key])) { $finalArray[$key] = $temp[$key] + $array[$key]; } else { $finalArray[$key] = $array[$key]; } } return $finalArray; } echo "<pre>"; print_r(moveArrayElementOnTop($C)); echo "</pre>";
Demo: https://3v4l.org/AVQBH