1

All,

I have the following array in array format. The JSON format is shown just for user-friendliness. How can I sort the array ascending with the key "name" in php?

            "food":
            [
                {
                    "id": 1,
                    "name": "dessert"
                },
                {
                    "id": 2,
                    "name": "maincourse"
                },
                {
                    "id": 3,
                    "name": "entrees"
                },
                {
                    "id": 4,
                    "name": "appetizers"
                }
            ]

The desired result is an array like this:

            "food":
            [
                {
                    "id": 4,
                    "name": "appetizers"
                },
                {
                    "id": 1,
                    "name": "dessert"
                },
                {
                    "id": 3,
                    "name": "entrees"
                },
                {
                    "id": 2,
                    "name": "maincourse"
                }
            ]
1
  • It might help clarify your question if you showed what result you would like for this input. Commented Apr 22, 2010 at 21:01

2 Answers 2

5

Use usort():

$array = array('food' => array(
        array(
            "id"=> 1,
            "name"=> "dessert"
        ),
        array(
            "id"=> 2,
            "name"=> "maincourse"
        ),
        array(
            "id"=> 3,
            "name"=> "entrees"
        ),
        array(
            "id"=> 4,
            "name"=> "appetizers"
        )
    )
);

function compare($a, $b) {
    return strcmp($a['name'], $b['name']);
}

usort($array['food'], 'compare');
print_r($array);
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the ksort() function (php.net/ksort)

ksort($array);

For example if you have an array:

$array = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($array);

It will sort them as a,b,c,d.

1 Comment

This assumes there's only 1 key. I have 2 keys. How to specify which key to sort on?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.