this is the array i like to sort in a particular order
$aData = Array
(
[break] => Array
(
[Indoor room] => 42
[Gym Class] => 19
)
[finish] => Array
(
[Indoor room] => 42
[Gym Class] => 19
)
[lunch] => Array
(
[Indoor room] => 7
)
[period1] => Array
(
[Indoor room] => 12
[Gym Class] => 22
)
[period2] => Array
(
[Gym Class] => 14
[Indoor room] => 25
)
[period3] => Array
(
[Gym Class] => 21
[Indoor room] => 11
)
[period4] => Array
(
[Gym Class] => 22
[Indoor room] => 20
)
[period5] => Array
(
[Gym Class] => 16
[Indoor room] => 9
)
)
But i like it in this order:
break, period1, period2, lunch, period3, period5, period6, finish
for this I am trying the following php code
$arraySort = [
"break",
"period1",
"period2",
"period3",
"lunch",
"period4",
"period5",
"period6",
"finish"
];
foreach($aData as $period => $catsScore){
echo 'test '.$period.'<br/>';
$periodItem = [$period];
foreach($arraySort as $cat){
echo 'new: '.$cat.'<br/>';
$periodItem[] = $catsScore;
}
$output[] = $periodItem;
}
print_r($output);
Death-is-the-real-truth
72.3k10 gold badges58 silver badges105 bronze badges
asked Dec 27, 2017 at 19:08
4 Answers 4
Easy- Just use the arraySort
as the assoc key and get the corresponding array / value from the original array,
<?php
$arraySort = [
"break",
"period1",
"period2",
"period3",
"lunch",
"period4",
"period5",
"period6",
"finish"
];
$final_array = [];
foreach($arraySort as $arraySo){
$final_array[$arraySo] = isset($aData[$arraySo]) ? $aData[$arraySo] : [];
}
print_r($final_array);
Output:- https://3v4l.org/4LXvS
answered Dec 27, 2017 at 19:12
Death-is-the-real-truth Death-is-the-real-truthDeath-is-the-real-truth
72.3k10 gold badges58 silver badges105 bronze badges
-
Thanks Alive, this is the one I understand. You just use the arraySort as the assoc key and get the corresponding array / value from the original array, right?alex– alex2017年12月27日 19:21:19 +00:00Commented Dec 27, 2017 at 19:21
Make correctly ordered array and fill it by value from source array
$final_array = array_replace(array_fill_keys($arraySort, []), $aData);
answered Dec 27, 2017 at 19:26
Alternatively you could use an actual sorting function:
uksort(
$aData,
function($a,$b)use($arraySort){
return array_search($a, $arraySort) - array_search($b, $arraySort);
}
);
answered Dec 27, 2017 at 19:51
you can use array_combine
for this purpose:
$arrary_sort = ["break", "period1"];
$final_array = array_combine($array_sort, $your_array_here);
answered Dec 27, 2017 at 19:16
-
2That will just "rename" the existing values, not reorder them correctlyMark Baker– Mark Baker2017年12月27日 19:30:48 +00:00Commented Dec 27, 2017 at 19:30
-
You change keys but don't reorder arraysplash58– splash582017年12月27日 19:31:45 +00:00Commented Dec 27, 2017 at 19:31
lang-php