-1

I have an array like this,

Output:

 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 Code:

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++;
}

i'm searching the data from array and want to sort it. Now when i print_r($eventperDayArray); it
I get output something like this now i want to sort it such that 0 index should come first and so on. I have used sort and ksort but it did'nt work it prints 1.

Dorian Turba
  • 1,818
  • 3
  • 20
  • 33
user3653474
  • 2,669
  • 3
  • 30
  • 83
  • 1
    `ksort` sorts the array provided, it doesn't return a sorted array. Use it, then look at what's in `$eventperDayData`. A return of `true` or `1` when you echo a bool, means it finished sorting. – Jonnix Jul 30 '19 at 09:25
  • 1
    What do you want to achieve? – splash58 Jul 30 '19 at 09:27

2 Answers2

1

use ksort() to sort by key

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
Janie
  • 633
  • 9
  • 25
1

ksort() does sort by keys on your array.

<?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);

Demo: https://3v4l.org/hkLCc

nice_dev
  • 14,216
  • 2
  • 21
  • 33