Robin Claes
Robin Claes

Reputation: 1

Sorting multidimensional array gives a wrong first item (starting with a P, instead of an A)

I've been helped sorting my multidimensional array by using the following code

<?php
    $guildname = str_replace(" ", "_", "Mutiny");
    $url = 'http://eu.battle.net/api/wow/guild/frostmane/'.$guildname.'?fields=members';
    $content = file_get_contents($url);
    $json = json_decode($content, true);

    array_multisort($json["members"], SORT_ASC);

    foreach($json["members"] as $item) 
    {                           
        echo 
        "<tr>
            <td>" . $item['character']['name'] . "</td>
            <td>" . $item['character']['class'] . "</td>
            <td>" . $item['rank'] . "</td>
        </tr>"
        ;
    }
?>      

Now the strange thing is, that my array sorts correctly, except for the first item. Check this image or the list below as an example:

Adding SORT_STRING does not work and gives an error.

Upvotes: 0

Views: 58

Answers (2)

RobinJ
RobinJ

Reputation: 5263

<?php
$json = file_get_contents ('https://eu.api.battle.net/wow/guild/Frostmane/Mutiny?fields=members&locale=en_GB&apikey=*');
$data = json_decode ($json, true);

$entries = $data['members'];

usort ($entries, 'sortByName');

var_dump ($entries);

function sortByName ($entry1, $entry2)
{
        $name1 = $entry1['character']['name'];
        $name2 = $entry2['character']['name'];

        return ord ($name1) - ord ($name2);
}
?>

Upvotes: 1

DrRoach
DrRoach

Reputation: 1356

You can use array_multisort() like so:

$array = array
(
[Baritone Horn] => Array
    (
        [0] => Array
            (
                [Name] => Baritone Maintenance
                [Order] => 12
                [CategoryID] => 13849839018
            )

        [1] => Array
            (
                [Name] => Baritone Mouthpieces
                [Order] => 13
                [CategoryID] => 13850963018
            )

        [2] => Array
            (
                [Name] => Accessories
                [Order] => 11
                [CategoryID] => 13850964018
            )

    ) 

[Alpen Horn] => Array
    (
        [0] => Array
            (
                [Name] => Baritone Maintenance
                [Order] => 12
                [CategoryID] => 13849839018
            )

        [1] => Array
            (
                [Name] => Baritone Mouthpieces
                [Order] => 13
                [CategoryID] => 13850963018
            )

        [2] => Array
            (
                [Name] => Accessories
                [Order] => 11
                [CategoryID] => 13850964018
            )

    ) 
)

array_multisort($array);

Upvotes: 0

Related Questions