If you want to sort chronologically, you don't need your $monthArray
variable. You can use strtotime()
to generate a timestamp from the month-year values and sort on these timestamps ascending. You can compare the values in the sort call by using the spaceship operator (<=>
) or if your php version is older, you can use subtraction.
Code: (Demo)
$result =[
["day" => "Feb 2018", "value" => "101"],
["day" => "Jan 2018", "value" => "18"],
["day" => "Mar 2018", "value" => "0"]
];
usort($result,function($a,$b){return strtotime($a['day'])-strtotime($b['day']);});
var_export($result);
Output:
array (
0 =>
array (
'day' => 'Jan 2018',
'value' => '18',
),
1 =>
array (
'day' => 'Feb 2018',
'value' => '101',
),
2 =>
array (
'day' => 'Mar 2018',
'value' => '0',
),
)
If your sorting month-year variable can contain non-chronological ordering, then you can use array_replace()
.
- Flip
$monthArray
so that the values become keys.
- Call
array_column()
with a null
2nd parameter so that the array is assigned keys using the column data dictated by the 3rd parameter.
- Replace
$monthArray
values based on associative keys.
- Reindex the array with
array_values()
.
Different Code, Same Result:
$monthArray = ["Jan 2018","Feb 2018","Mar 2018"];
$result =[
["day" => "Feb 2018", "value" => "101"],
["day" => "Jan 2018", "value" => "18"],
["day" => "Mar 2018", "value" => "0"]
];
$result = array_values(array_replace(array_flip($monthArray),array_column($result,null,'day')));
var_export($result);
Depending on the size of your input data, this may or may not be faster than usort()
with two array_search()
calls on each iteration. Either way the speed difference will be unnoticeable to your end users.