简体   繁体   中英

Sort multidimensional and associative array by a deeply nested array in PHP

I have a multidimensional array that I fetch from a database and it's structured like this:

array(SESSION
      array(items
            array(DatabaseID
                  (ItemName, ItemCategory, Children, 
                                                    array(Id1, Id2, Id3...)         
                                                       etc..))))

I am not sure that this is how you write it since I'm a beginner but I hope you get the struture. If I want to acess the ItemCategory of a certain item, I save the item's DatabaseID in $DatabaseID and write:

$_SESSION['items'][$DatabaseID]['ItemCategory'];

If I want an array with the items children's DatabaseID I write:

$_SESSION['items'][$DatabaseID]['Children'];

Now, I want to sort this array. I have looked around but I don't understand how to sort it after exactly what I want. I would like to sort the whole

$_SESSION['items']

according to the ItemName instead of the DatabaseID. Is this at all possible? I mean, the ItemName is stored for each DatabaseID...

I want to use this in order print all the Items sorted by their name instead of their DatabaseID.

Edit

I have tried

array_multisort($_SESSION['items'], $_SESSION['items']['DatabaseID']['ItemName']);

but the problem is that

 $_SESSION['items']['DatabaseID']['ItemName']

is not an array.

An easier and faster solutiom is to use the SQL ORDER BY clause.

The syntax is:

SELECT column1, column2, ... FROM table_name ORDER BY column1, column2, ... ASC|DESC;

You should add this clause onto your existing SQL statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM