skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. $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 the foreach-loop (at the end of your comment) because its already "looped" within one call.

    best regards

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search