Home > Software design >  Alphabetically sort array of objects based on property value php
Alphabetically sort array of objects based on property value php

Time:01-12

I'm struggling to sort my array of objects into alphabetical order by the title key. Getting error that 'title' is undefined.

I want to go from this:

My Array
(
    [0] => Array
        (
            [area] => TACT
            [pages] => Array
                (
                    [0] => Array
                        (
                            [id] => 1484
                            [title] => Registry
                        )

                    [1] => Array
                        (
                            [id] => 1385
                            [title] => Education

To:

My Array
(
    [0] => Array
        (
            [area] => TACT
            [pages] => Array
                (
                    [0] => Array
                        (
                            [id] => 1385
                            [title] => Education
                        )

                    [1] => Array
                        (
                            [id] => 1484
                            [title] => Registry

Have tried:

function sort_alpha_title($a, $b) {
    return strnatcmp($a['title'], $b['title']);
}

usort($myArray, 'sort_alpha_title');

CodePudding user response:

You should use

function sort_alpha_title($a, $b) {
  return strnatcmp($a['title'], $b['title']);
}

usort($myArray[0]['pages'], 'sort_alpha_title');

Because the title property is a child property of the pages property.

CodePudding user response:

$myArray = array(
    array(
        'area' => 'TACT',
        'pages' => array(
            array(
                'id' => 1484,
                'title' => 'Registry'
            ),
            array(
                'id' => 1385,
                'title' => 'Education'
            )
        )
    )
);

function sort_alpha_title($a, $b)
{
    return strnatcmp($a["title"], $b["title"]);
}

usort($myArray[0]['pages'], 'sort_alpha_title');
var_dump($myArray);

Sry for the doubled answer but i cant add a comment because of my reputation. tomhuckle wrote

thanks! this works. But only for one of my objects in the array. Sorry the description should of said. ive tried putting a for each loop but that's not working. here's what i tried: foreach($myArray as $a) { usort($a['pages'], 'sort_alpha_title'); }

you dont need a loop because its already looped :)

best regards

  • Related