Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array with weekday keys by weekday order

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.

like image 939
Chirag Pipariya Avatar asked Feb 12 '14 04:02

Chirag Pipariya


1 Answers

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
)
like image 172
Shankar Narayana Damodaran Avatar answered Sep 28 '22 01:09

Shankar Narayana Damodaran