gpt4 book ai didi

PHP 和 MySQL 以嵌套数组的形式获取结果

转载 作者:行者123 更新时间:2023-11-29 23:52:50 24 4
gpt4 key购买 nike

我有这些代码行,根据制造商填充计算机列表:

<?php 
$query = "
SELECT m.manufacturerName
, c.id
, c.computerName
, GROUP_CONCAT(c.model SEPARATOR ',') clients
, c.computerName
FROM manufacturers m
JOIN computers c
ON c.manufacturerId = m.id
GROUP
BY m.id;
";

$manufacturers = array();

if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$manufacturers[$row['manufacturerName']] = explode(',', $row['clients']);
}
}

foreach ($manufacturers as $manufacturer => $clients) {
echo '<div class="listview-outlook" data-role="listview">';
echo '<div class="list-group">';
echo '<a href="#" class="group-title">' . $manufacturer . '</a>';

foreach ($clients as $client) {
echo '<div class="group-content">';
echo '<a href="/edit/computer.php?id=' . /* client id should be here */ . '" class="list">';
echo '<div class="list-content">' . $client .'</div>';
echo '</a>';
echo '</div>';
}

echo '</div>';
echo '</div>';
}
?>

为了在第二个 foreach 循环(第 20 行)内显示表列 c.id 的结果,我应该做什么?

我知道我需要用 id 构建数组,但是如何构建呢?我对编程还很陌生,所以请耐心等待!

最佳答案

试试这个:

<?php 
$query = "SELECT m.manufacturerName, c.id, c.computerName, group_concat(c.model SEPARATOR ',') AS clients, c.computerName FROM manufacturers m ";
$query .= "INNER JOIN computers c ON c.manufacturerId = m.id GROUP BY m.id";

$manufacturers = array();

if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$manufacturers[$row['manufacturerName']] = $row;
$manufacturers[$row['manufacturerName']]['clients'] = explode(',', $row['clients']);
}
}

foreach ($manufacturers as $manufacturer => $data) {
echo '<div class="listview-outlook" data-role="listview">';
echo '<div class="list-group">';
echo '<a href="#" class="group-title">' . $manufacturer . '</a>';

foreach ($data['clients'] as $client) {
echo '<div class="group-content">';
echo '<a href="/edit/computer.php?id=' . $data['id'] . '" class="list">';
echo '<div class="list-content">' . $client .'</div>';
echo '</a>';
echo '</div>';
}

echo '</div>';
echo '</div>';
}
?>

关于PHP 和 MySQL 以嵌套数组的形式获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25526089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com