来自匹配mysql列的多维数组[关闭]
Posted
技术标签:
【中文标题】来自匹配mysql列的多维数组[关闭]【英文标题】:Multi-Dimensional Array from matching mysql columns [closed] 【发布时间】:2016-12-20 20:26:38 【问题描述】:我有一个包含行业和类别的表格,如下所示。
id|industry|category |
1 |Building|Air Conditioning|
2 |Building|Roofing |
3 |Security|Cameras |
我正在尝试返回一个数组,如下所示
array(
"Building" => array(
"Air Conditioning",
"Roofing",
),
"Security" => array(
"Cameras",
),
);
解决这个问题的最佳方法是什么。
提前感谢您的帮助。
【问题讨论】:
【参考方案1】:试试这个:
$query = mysql_query('select * from table');
foreach ($data = mysql_fetch_object($query))
$array[$data->industry][] = $data->category;
print_r($array);
【讨论】:
【参考方案2】:只需遍历数据一次:
$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);
Link to Fiddle
【讨论】:
感谢这是最好的回应,非常感谢您的知识。【参考方案3】:$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);
【讨论】:
以上是关于来自匹配mysql列的多维数组[关闭]的主要内容,如果未能解决你的问题,请参考以下文章