简体   繁体   English

如何排序查询结果在PHP?

[英]how to sort query result in php?

I am trying to sort query result into an array. 我正在尝试将查询结果排序到数组中。

I have following query. 我有以下查询。

"select s.*, a.* from students left join addresses as a";

it returns 它返回

s.id
s.name
a.id
a.student_id
a.address

I would like to make above result into an array with s and a keys. 我想将上面的结果做成一个带有s和一个键的数组。

array(
  "s"=>array("id"=>"value","name"=>"value")
  ,"a"=>array("id"=>"value","student_id"=>"value","address"=>"value)
)

do I have to make my own function to do it or is there an internal function? 我必须自己编写函数才能执行此操作,还是有内部函数?

You have to do it yourself if for no other reason than the table isn't identifiable in PHP from the query result. 如果除了查询结果中无法在PHP中识别该表以外,您必须自己做。 You only get the column name. 您只会得到列名称。

Aside: In your current code I believe s.id will get overwritten by a.id if you select rows as associative arrays. 另外: 在您当前的代码中,如果您选择行作为关联数组,我相信s.id将被a.id覆盖。

Now, on to one possible approach... 现在,介绍一种可能的方法...

One aspect of how the results are returned is you lose the table from which the column came. 如何返回结果的一方面是您丢失了列所在的表。 If you find yourself wanting to do post-processing on the resultset, perhaps you could alias each column by renaming it like so: 如果您发现自己想对结果集进行后处理,则可以通过如下重命名来对每列进行别名:

$query = "SELECT
    s.id         AS s_id
    s.name       AS s_name
    a.id         AS a_id
    a.student_id AS a_student_id
    a.address    AS a_address
    ... ";

Once you have that you can organize the data based on substr($key,0,1) and get the "underlying column name with substr($key,2). 一旦有了,就可以基于substr($ key,0,1)整理数据,并获得带有substr($ key,2)的“基础列名称”。

Once you have those you can loop inside each row to create the data structure you want to work with. 一旦有了它们,就可以在每一行中循环以创建要使用的数据结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM