Mike
Mike

Reputation: 1261

PHP Sort array by name

The data returning from my database is encrypted. so running a order by at the end of the SQL is not working. so I have to sort on the server side.

I see a lot a question about this I have tried a suggestions but I can't seem to get to sort . I tried this routine and this one (look like the closest to what I was looking for).

2 things are happening:

1: It don't sort by the name field(key)

2: Our in house app complains that its not a JSON string any longer.

I need to sort this my the name, so I need a custom sort

I get my array set like this:

$jsonData = array();

...connected to the DB.... stuff here...
//loop through the return:

if($result->num_rows > 0)
     {
        while($row = $result->fetch_assoc())
         {
               $row["name"] = $this->decryptData($row["name"]);
              $jsonData["groups"][] = $row ;

         }   

}


    $result->close();   
    mysqli_close($mysqli);
    return $jsonData;

The return code looks like this:

{
  "groups": [
    {
      "id": "71",
      "name": "Bob",
       },
    {
      "id": "73",
      "name": "Howard",
    },
    {
      "id": "79",
      "name": "Sam",

    },....
  ....{
      "id": "65",
      "name": "Al",

    }
  ]
}

OK so I added this code at the bottom of my routine to sort (notice I tried to methods):

.... code

        /*usort($jsonData, function($a, $b) {
           return $a['name'] - $b['name'];
        });*/

         usort($jsonData, function($a, $b) {
         return strcasecmp($a['name'], $b['name']);
         });

    /* and I tried this get the same output but with a php error say what I have is not a array
        array_multisort($jsonData['name']);
          -- and this--
        array_multisort($jsonData['groups']['name']);

   */



$result->close();   
        mysqli_close($mysqli);
        return $jsonData;

and I get this result which is little different than what I need and its not sorted by name:

[
   [
        {
          "id": "71",
          "name": "Bob",
           },
        {
          "id": "73",
          "name": "Howard",
        },
        {
          "id": "79",
          "name": "Sam",

        },....
      ....{
          "id": "65",
          "name": "Al",

        }
      ]
]

I'm lost at the moment.

Upvotes: 1

Views: 2579

Answers (2)

ryvasquez
ryvasquez

Reputation: 158

You can use usort

usort($jsonData['group'], function($a, $b) { return $a['name'] - $b['name']; });

and try to print_r($jsonData)

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173642

You can't apply arithmetics to string values for comparisons; you need a string function instead, such as strcmp() or strcasecmp() which return a value of -1, 0, or 1:

usort($jsonData, function($a, $b) {
    return strcasecmp($a['name'], $b['name']);
});

Upvotes: 1

Related Questions