douguadao3883
2014-11-25 02:47
浏览 44
已采纳

PHP按名称排序数组

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.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanlei5339 2014-11-25 02:50
    已采纳

    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']);
    });
    
    评论
    解决 无用
    打赏 举报
  • 查看更多回答(1条)

相关推荐 更多相似问题