我有这种排序算法来对$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] =>
)
答案 0 :(得分:2)
您的代码应该说$daysAux[$k] =
而不是$daysAux[$key] =
如果$key
为false
,则会覆盖相同的条目,而不是创建新条目
还需要在循环中交换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);