如何使用php从mysql获取数据来对JSON数据进行排序

时间:2016-01-25 16:39:30

标签: php json

你好我们正在尝试排序json数据,但我不知道该怎么做。需要它为我的Android应用程序,我想尝试使用ID来缩短数据。提前谢谢。

 <?php

require "init.php";   // This file provide the connetion 


header('Content-type:application/json');

$result = mysqli_query($con,"SELECT * from post_s order ('post_id DESC')");

$rows= array();

while ($row=mysqli_fetch_array($result)) {
    $rows[] = array('post_id'=>$row['post_id'],'user_id'=>$row['user_id'],'user_name'=>$row['user_name'],'post_title'=>$row['post_title'],'likes'=>$row['likes'],'post_cat'=>$row['post_cat'],'post_time'=>$row['post_time']);

}


if (json_encode($rows) == '[]') 

    echo "No new posts found !! ";

    else echo json_encode(array("post"=>$rows));


?>

此文件将提供类似

的json输出
{
 "post":
    [
       {
         "post_id":"7001",
         "user_id":"1001",
         "user_name":"qwerty asdfg",
         "post_title":"check this post",
         "likes":"456",
         "post_cat":"ghghjg",
         "post_time":"45632"
       },
       {
         "post_id":"7002",
         "user_id":"0984",
         "user_name":"abcd efgh",
         "post_title":"hello guys perfect post",
         "likes":"123",
         "post_cat":"mobile",
         "post_time":"12345"
       }
    ]
}

但我需要像

一样输出
{
 "post":
    [
       {
         "post_id":"7002",
         "user_id":"0984",
         "user_name":"abcd efgh",
         "post_title":"hello guys perfect post",
         "likes":"123",
         "post_cat":"mobile",
         "post_time":"12345"
       },
       {
         "post_id":"7001",
         "user_id":"1001",
         "user_name":"qwerty asdfg",
         "post_title":"check this post",
         "likes":"456",
         "post_cat":"ghghjg",
         "post_time":"45632"
       }
    ]
}

再次感谢你的帮助

1 个答案:

答案 0 :(得分:0)

使用=--CONCATENATESPECIAL(H1)

usort

或者在PHP 7中使用usort($rows, function($a, $b){ return (((int) $a["post_id"]) > ((int) $b["post_id"])) ? 1 : 0; }); 太空飞船运算符