无法对数组索引 php 进行排序

Cannot sort array index php

我有一个这样的数组,

输出:

 Array
    (
        [3] => stdClass Object
            (
                [id] => 11591
                [title] => abc
            )

        [2] => stdClass Object
            (
                [id] => 11592
                [title] => xyz
            )

        [0] => stdClass Object
            (
                [id] => 11589
                [title] => abg
            )

        [1] => stdClass Object
            (
                [id] => 11590
                [title] => asw
            )

    )

Codeigniter 代码:

foreach($results as $rowData)
{
    if($rowData->title=='xyz')
    {
        $eventperDayArray['0']=$rowData;
    }
    else if($rowData->title=='asw')
    {
        $eventperDayArray['1']=$rowData;
    }
    else if($rowData->title=='abc')
    {
        $eventperDayArray['2']=$rowData;
    }
    else if($rowData->title=='abg')
    {
        $eventperDayArray['3']=$rowData;
    }
    if($i==5)
    {
        print_r($eventperDayArray);
        die();
        break;
    }
    $i++;
}

我正在从数组中搜索数据并想对其进行排序。现在当我 print_r($eventperDayArray);
我得到这样的输出,现在我想对它进行排序,以便 0 索引应该排在第一位,依此类推。 我已经使用了 sortksort 但它没有工作它打印 1.

使用 ksort() 按键排序

foreach($results as $rowData) {
if ($rowData->title == 'MORNING') {
    $eventperDayArray['0'] = $rowData;
} else if ($rowData->title == 'AFTERNOON') {
    $eventperDayArray['1'] = $rowData;
} else if ($rowData->title == 'EVENING') {
    $eventperDayArray['2'] = $rowData;
} else if ($rowData->title == 'NIGHT') {
    $eventperDayArray['3'] = $rowData;
}
if ($i == 5) {
    print_r($eventperDayArray);
    die();
    break;
}
$i++;
}

ksort($eventperDayArray);

eventperDayArray

ksort() 确实按数组中的键排序。

<?php

$arr = [];
$o = new stdclass();
$o->id = 11591;
$o->title = 'abc';
$arr[3] = $o;
$o = new stdclass();
$o->id = 11592;
$o->title = 'xyz';
$arr[2] = $o;
$o = new stdclass();
$o->id = 11589;
$o->title = 'abg';
$arr[0] = $o;
$o = new stdclass();
$o->id = 11590;
$o->title = 'asw';
$arr[1] = $o;

ksort($arr);
print_r($arr);

演示: https://3v4l.org/hkLCc