I want to sort array with weekday keys in the order of the week, like this: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday.
Given input like this:
Array
(
[Thursday] => 8
[Friday] => 7
[Monday] => 9
[Tuesday] => 12
[Wednesday] => 8
[Saturday] => 17
)
I want a result like this:
Array
(
[Monday] => 9
[Tuesday] => 12
[Wednesday] => 8
[thusday] => 8
[friday] => 7
[Saturday] => 17
)
Please Help.
The following code does not make use of any sorting functions .. In other words.. a sort is unnecessary in this context.
<?php
//Your actual array...
$arr=Array (
'Thursday' => 8,
'Friday' => 7,
'Monday' => 9,
'Tuesday' => 12,
'Wednesday' => 8,
'Saturday' => 17
);
//This is the template array.. Changing this alters the output
$arr2=array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
//A simple loop that traverses all elements of the template...
foreach($arr2 as $v)
{
//If the value in the template exists as a key in the actual array.. (condition)
if(array_key_exists($v,$arr))
{
$arr4[$v]=$arr[$v]; //The value is assigned to the new array and the key of the actual array is assigned as a value to the new array
}
}
//prints the new array
print_r($arr4);
OUTPUT :
Array
(
[Monday] => 9
[Tuesday] => 12
[Wednesday] => 8
[Thursday] => 8
[Friday] => 7
[Saturday] => 17
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With