我有一张包含电机名称和电机描述的表格。有几个具有相同名称的电机具有不同的描述。
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
我已经在这里待了大约一个小时,但没有运气。
答案 0 :(得分:1)
此查询将以逗号分隔结果,然后您可以使用explode函数来解析结果,
SELECT NAME, GROUP_CONCAT(DESCRIPTION) AS description
FROM motor_table GROUP BY name
答案 1 :(得分:0)
如果我正确理解了您的问题,那么您可以在查询中使用GROUP BY
子句:
SELECT * FROM motor_table
GROUP BY name
答案 2 :(得分: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;
答案 3 :(得分: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 )
)