我有一个包含行业和类别的表格如下所示。
id|industry|category |
1 |Building|Air Conditioning|
2 |Building|Roofing |
3 |Security|Cameras |
我正在尝试按如下方式返回数组
array(
"Building" => array(
"Air Conditioning",
"Roofing",
),
"Security" => array(
"Cameras",
),
);
解决此问题的最佳方法是什么。
感谢您提前提供任何帮助。
答案 0 :(得分:1)
试试这个:
$query = mysql_query('select * from table');
foreach ($data = mysql_fetch_object($query)) {
$array[$data->industry][] = $data->category;
}
print_r($array);
答案 1 :(得分:0)
只需对数据进行一次迭代:
$data = [
[1, "Building", "Air Conditioning"],
[2, "Building", "Roofing"],
[3, "Security", "Cameras"]
];
$result = [];
foreach ($data as $row) {
if (!array_key_exists($row[1], $result)) {
$result[$row[1]] = [];
}
array_push($result[$row[1]], $row[2]);
}
var_dump($result);
答案 2 :(得分:0)
$tbl_industries = array(
array(
'id' => 1,
'industry' => 'Building',
'category' => 'Air Conditioning'
),
array(
'id' => 2,
'industry' => 'Building',
'category' => 'Roofing'
),
array(
'id' => 3,
'industry' => 'Security',
'category' => 'Cameras'
)
);
foreach($tbl_industries as $industry) {
$industry_name = $industry['industry'];
$industries[$industry_name][] = $industry['category'];
}
var_dump($industries);
或强>
包含数据库交互的代码:
$con = mysqli_connect('localhost', 'root', '', 'db_name');
$query = "SELECT * FROM tbl_industries";
if($result = mysqli_query($con, $query)) {
while($industry = mysqli_fetch_assoc($result)) {
$industry_name = $industry['industry'];
$industries[$industry_name][] = $industry['category'];
}
mysqli_free_result($result);
var_dump($industries);
}