我有以下数组:
$days = array(1, 2, 3, 4, 5, 6, 0);
我选择的值是4
,我可以得到一个数组:
$result = array(4, 5, 6, 0, 1, 2, 3);
使用以下代码:
$days = array(1, 2, 3, 4, 5, 6, 0);
$split_by = array_search(4, $days);
if ($split_by) {
$first = array_slice($days, 0, $split_by);
$second = array_slice($days, $split_by);
}
$result = array_merge($second, $first);
print_r($result);
但是当我将选定的值作为1
传递时,它会给我null数组。
答案 0 :(得分:1)
$split_by
并且0
松散地等同于1
时, 0
为索引false
,因此您的if
语句失败并且未创建$first
和second
数组。与false
进行严格比较:
if ($split_by !== false) {
您也可能希望在if
中进行合并:
if ($split_by !== false) {
$first = array_slice($days, 0, $split_by);
$second = array_slice($days, $split_by);
$result = array_merge($second, $first);
} else {
$result = false; //or something
}
答案 1 :(得分:0)
It will be work fine now use the code :
$days = array(1, 2, 3, 4, 5, 6, 0);
$split_by = array_search(1, $days);
if (isset($split_by)) {
$first = array_slice($days, 0, $split_by);
$second = array_slice($days, $split_by);
}
$result = array_merge($second, $first);
print_r($result);