按工作日顺序对带有工作日键的数组进行排序
Posted
技术标签:
【中文标题】按工作日顺序对带有工作日键的数组进行排序【英文标题】:Sort array with weekday keys by weekday order 【发布时间】:2014-03-10 05:32:18 【问题描述】:我想按星期顺序使用工作日键对数组进行排序,如下所示:星期一、星期二、星期三、星期四、星期五、星期六。
给定这样的输入:
Array
(
[Thursday] => 8
[Friday] => 7
[Monday] => 9
[Tuesday] => 12
[Wednesday] => 8
[Saturday] => 17
)
我想要这样的结果:
Array
(
[Monday] => 9
[Tuesday] => 12
[Wednesday] => 8
[thusday] => 8
[friday] => 7
[Saturday] => 17
)
请帮忙。
【问题讨论】:
【参考方案1】:以下代码没有使用任何排序功能..换句话说..在这种情况下不需要排序。
<?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
)
【讨论】:
@ChiragPipariya,修改了新代码并删除了不必要的功能,还添加了 cmets,以便您了解代码上正在执行的操作。【参考方案2】:使用uksort
.这是一种方法:
$week_order = array_flip(array('Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday'));
$data = array('Thursday' => 8, 'Friday' => 7, 'Monday' => 9, 'Tuesday' => 12,
'Wednesday' => 8, 'Saturday' => 17);
uksort($data,
function($a, $b) use ($week_order) return $week_order[$a] - $week_order[$b]; );
print_r($data);
【讨论】:
【参考方案3】:有很多方法可以做到这一点,但使用array_merge
相当简单
$d = array(
'Sunday' => '',
'Monday' => '',
'Tuesday' => '',
'Wednesday' => '',
'Thursday' => '',
'Friday' => '',
'Saturday' => '',
);
$n = array
(
'Thursday' => 8,
'Friday' => 7,
'Monday' => 9,
'Tuesday' => 12,
'Wednesday' => 8,
'Saturday' => 17,
);
var_dump(array_filter(array_merge($d,$n)));
array_filter
删除空值给你这个:
array(6)
["Monday"]=>
int(9)
["Tuesday"]=>
int(12)
["Wednesday"]=>
int(8)
["Thursday"]=>
int(8)
["Friday"]=>
int(7)
["Saturday"]=>
int(17)
没有它,你会有这样的:
array(7)
["Sunday"]=>
string(0) ""
["Monday"]=>
int(9)
["Tuesday"]=>
int(12)
["Wednesday"]=>
int(8)
["Thursday"]=>
int(8)
["Friday"]=>
int(7)
["Saturday"]=>
int(17)
注意“星期日”的空值
也可以通过简单的循环来完成:
$d = array(
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
);
$n = array (
'Thursday' => 8,
'Friday' => 7,
'Monday' => 9,
'Tuesday' => 12,
'Wednesday' => 8,
'Saturday' => 17,
);
$sorted = array();
foreach ($d as $k)
if (isset($n[$k]))
$sorted[$k] = $n[$k];
var_dump($sorted);
【讨论】:
以上是关于按工作日顺序对带有工作日键的数组进行排序的主要内容,如果未能解决你的问题,请参考以下文章