douyun1860 2014-10-11 04:40
浏览 92

按行值对数据库行数组进行排序

Here is my PHP script. What I wish to do is to sort the response array by a key. The key that I wish to sort the array by is a component of the row. To better clarify, say the row contained a string and an int type object. How can I sort the array using the int object as key? I have looked at ksort() and understand how to use it but I am unsure how to use it in the way that I am attempting to.

<?php

// array for JSON response
$response = array();


$host = "localhost"; //server
$db = "Test"; //database name
$user = "root"; //dabases user name
$pwd = "xxxxxxx"; //password


    $link = mysqli_connect($host, $user, $pwd, $db);
    $result = mysqli_query($link, "SELECT * FROM Table");


    // check for empty result
    if (mysqli_num_rows($result) > 0) 
    {

        $response["stuff"] = array();
        $event = "";

         while ($row = mysqli_fetch_array($result)) {

            $event = $row;
            $response[] = event;

         } 

      //Here I wish to sort the array by the int object as key.
     $response["success"] = 1;

    echo json_encode($response);
}
 ?>
  • 写回答

1条回答 默认 最新

  • duangang79177 2014-10-11 07:15
    关注

    The comments above might answer this specific requirement, but I would like to also describe how to sort a PHP array like the question poster wants to:

    The method of choice is not ksort() (sort by key), but
    usort (&$array, $value_compare_func) (sort by user-defined callback):

    usort($response['stuff'], function($a, $b) {
        return $a['integer'] - $b['integer'];
    });
    

    Where the closure function is a simple integer comparison using array members as operands (with key integer in this example).
    When comparing other types of values, the comparison function should be adapted to meet the requirements of usort(). E.g. for strings, one would use strcmp().

    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用