0
    [sections] => stdClass Object
            (
                [22353] => stdClass Object
                    (
                        [id] => 2
                        [section_start_date] => 1410235200
                    )

                [22354] => stdClass Object
                    (
                        [id] => 1
                        [section_start_date] => 1410235260

                    )
)

How do I sort the above objects in PHP by the id, while preserving the keys of the sections object? For instance I want to show 22354 on top of 22353. Since these are objects the keys are technically just strings to me but I need to keep them in tact.

There is some confusion going on. These are objects which are not in an array. Pay close attention to the section object.

allencoded
  • 7,015
  • 17
  • 72
  • 126

1 Answers1

1

this is how you do it

stdClass Object
(
    [111111] => stdClass Object
        (
           [id] => 2
           [section_start_date] => 1410235200
       )
    [999999] => stdClass Object
       (
            [id] => 1
            [section_start_date] => 1410235260
       )

    [222222] => stdClass Object
        (
            [id] => 1
            [section_start_date] => 1410235300
    )
    [555555] => stdClass Object
        (
            [id] => 1
            [section_start_date] => 1410231160
        )
)

Steps Convert stdClass to array

$data = json_decode(json_encode($object),true);
ksort($data);
print_r($data);

output new sorted array while maintaining key index.

Array
(
    [111111] => Array
        (
            [id] => 2
            [section_start_date] => 1410235200
        )
    [222222] => Array
        (
            [id] => 1
            [section_start_date] => 1410235300
        )
    [555555] => Array
        (
            [id] => 1
            [section_start_date] => 1410231160
        )
    [999999] => Array
        (
           [id] => 1
           [section_start_date] => 1410235260
        )
)
mdamia
  • 4,447
  • 1
  • 24
  • 23