数组值按选定值排列

时间:2017-06-27 17:28:50

标签: php arrays

我有以下数组:

$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数组。

2 个答案:

答案 0 :(得分:1)

当您搜索$split_by并且0松散地等同于1时,

0为索引false,因此您的if语句失败并且未创建$firstsecond数组。与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);