在php与mysql中对数据进行排序多少钱?

时间:2022-05-09 07:46:42

I'd like to group an array that I've returned from a mysql database. I've named the array $item_info and I'd like to group it by folder_id.

我想将我从mysql数据库返回的数组分组。我已将数组命名为$ item_info,我想按folder_id对其进行分组。

First, two related questions:

首先,两个相关的问题:

  1. Is doing a single query to get the data below and creating new array keys always (or most likely) faster than 2 separate queries (one involving the desired GROUP BY and the other not).
  2. 正在执行单个查询以获取下面的数据并始终(或最可能)创建新的数组键比2个单独的查询(一个涉及所需的GROUP BY而另一个不涉及)。
  3. From what I read on SO it seems it is best to keep the MySQL query simple and sort out the data with PHP. Comments on that general philosophy?
  4. 从我读到的内容看来,最好保持MySQL查询简单并用PHP整理数据。评论一般哲学?

here's what my database gives back:

这是我的数据库回馈的内容:

$item_info=array(
 array("id"=>"1", 'folder_id'="1", "img"=>"/images/button_01.gif"),
 array("id"=>"2", 'folder_id'="1", "img"=>"/images/button_02.gif"),
 array("id"=>"3", 'folder_id'="2",  "img"=>"/images/button_03.gif"),
 array("id"=>"4", 'folder_id'="2", "img"=>"/images/button_04.gif"),
 array("id"=>"5", 'folder_id'="3", "img"=>"/images/button_05.gif"),
 array("id"=>"6", 'folder_id'="3", "img"=>"/images/button_06.gif")
);

here's how i'd like to array:

这是我想要的数组:

$item_info=array(
 array(
   array("id"=>"1", 'folder_id'="1", "img"=>"/images/button_01.gif"),
   array("id"=>"2", 'folder_id'="1", "img"=>"/images/button_02.gif")
 ),
 array(
   array("id"=>"3", 'folder_id'="2",  "img"=>"/images/button_03.gif"),
   array("id"=>"4", 'folder_id'="2", "img"=>"/images/button_04.gif")
 ),
 array(
   array("id"=>"5", 'folder_id'="3", "img"=>"/images/button_05.gif"),
   array("id"=>"6", 'folder_id'="3", "img"=>"/images/button_06.gif")
 ));

1 个解决方案

#1


3  

Since you already have the data in RAM, grouping in PHP seems more than reasonable, since it takes not a lot of processing.

由于您已经在RAM中拥有数据,因此在PHP中进行分组似乎更合理,因为它不需要大量处理。

You might want to try

你可能想试试

$item_info_tmp=array();
foreach ($item_info as $ii) {
    if (!isset($item_info_tmp[$ii['folder_id']]))
        $item_info_tmp[$ii['folder_id']]=array();
    $item_info_tmp[$ii['folder_id']][]=$ii;
}
$item_info=array_values($item_info_tmp);

#1


3  

Since you already have the data in RAM, grouping in PHP seems more than reasonable, since it takes not a lot of processing.

由于您已经在RAM中拥有数据,因此在PHP中进行分组似乎更合理,因为它不需要大量处理。

You might want to try

你可能想试试

$item_info_tmp=array();
foreach ($item_info as $ii) {
    if (!isset($item_info_tmp[$ii['folder_id']]))
        $item_info_tmp[$ii['folder_id']]=array();
    $item_info_tmp[$ii['folder_id']][]=$ii;
}
$item_info=array_values($item_info_tmp);