不显示php中ksort的最后一个值

时间:2018-06-09 08:30:06

标签: php sorting

我有这种排序算法来对$days引用$daysOfWeek进行排序,但我不确定为什么最后一个值不包含在我的数组中。这是下面的代码

#default array
$daysOfWeek = array('M','T','W','TH','F');
#your array
$days = array('T','W','TH','','');
#create a new array with key association property
$daysAux = array();
foreach($days as $k=>$v) {
    $key = array_search($v, $daysOfWeek);
    if($key !== FALSE) {
        $daysAux[$key] = $v;
    }
    else
        $daysAux[$key] = '';
    }
# array before sort
echo '<pre/>';print_r($daysAux);
ksort($daysAux);
$days = $daysAux;
#final result
echo '<pre/>';print_r($days);


#output
Array
(
 [1] => T
 [2] => W
 [3] => TH
 [0] => 
)
Array
(
 [0] => 
 [1] => T
 [2] => W
 [3] => TH
)

EXPECTED OUTPUT:
Array
(
[0] =>
[1] => T
[2] => W
[3] => TH
[4] => 
)

1 个答案:

答案 0 :(得分:2)

您的代码应该说$daysAux[$k] =而不是$daysAux[$key] =

如果$keyfalse,则会覆盖相同的条目,而不是创建新条目

还需要在循环中交换daysdaysOfWeek

#default array
$daysOfWeek = array('M','T','W','TH','F');
#your array
$days = array('T','W','TH','','');
#create a new array with key association property
$daysAux = array();
foreach($days as $k=>$v) {
    $key = array_search($v, $daysOfWeek);
    if($key !== FALSE) {
        $daysAux[$key] = $v;
    }
    else
        $daysAux[$key] = '';
    }
# array before sort
echo '<pre/>';print_r($daysAux);
ksort($daysAux);
$days = $daysAux;
#final result
echo '<pre/>';print_r($days);