0

我有一张包含电机名称和电机描述的表格。有几个电机彼此同名,但描述不同。

Example:

motor_table


NAME       DESCRIPTION
Evinrude   90HP ETEC
Evinrude   150HP ETEC
Mercury    90HP 4/S
Mercury    150HP 4/S

我想遍历表并为每个不同的名称创建一个数组,但我不希望名称重复。所以电机名称数组看起来像这样。

$motor_names = array('Evinrude','Mercury');

然后我想使用数组来像这样显示表中的数据。

EVINRUDE
90HP ETEC
150HP ETEC

MERCURY
90HP 4/S
150HP 4/S

我已经在这里待了大约一个小时,但没有任何运气。

4

4 回答 4

1

该查询将以逗号分隔的结果给出结果,然后您可以使用explode函数解析结果,

SELECT NAME, GROUP_CONCAT(DESCRIPTION) AS description
  FROM motor_table GROUP BY name
于 2013-07-05T13:57:07.437 回答
0

这有点复杂,但您可以在 SQL 查询中完成:

select name
from ((select name, name as sort1, 0 as sort2
       from motor_table
      ) union all
      (select description, name as sort1, 1 as sort2
       from motor_table
      )
     ) t
order by sort1, sort2;

这实际上没有空行。你可以这样做:

select name
from ((select name, name as sort1, 0 as sort2
       from motor_table
      ) union all
      (select description, name as sort1, 1 as sort2
       from motor_table
      ) union all
      (select '', name as sort1, 2 as sort2
       from motor_table
      )
     ) t
order by sort1, sort2;
于 2013-07-05T13:58:49.020 回答
0

如果我正确理解您的问题,那么您可以在查询中使用GROUP BY子句:

SELECT * FROM motor_table GROUP BY name

于 2013-07-05T13:57:38.217 回答
0
<?php
$array= array(
array('name' => 'Evinrude', 'description' =>   "90HP ETEC"),
array('name' => 'Mercury', 'description' =>   "90HP 4/S"),
array('name' => 'Mercury', 'description' =>   "150HP 4/S")
);

$motor_names = array('Evinrude','Mercury');
$data = array();
foreach($array as $row)
{
  $data[$row['name']][] = $row['description'];
}


print_r($data);

?>

使用此代码

输出:

Array ( 
         [Evinrude] => Array ( [0] => 90HP ETEC )
         [Mercury] => Array ( [0] => 90HP 4/S [1] => 150HP 4/S ) 
      )
于 2013-07-05T13:59:39.260 回答