我正在尝试将MySQL结果放入数组中,以便为相关产品创建标题。我遇到了与此特定代码的问题。我不太理解该错误,但我假设它必须与数组中的格式和结构有关。
foreach ($equipTitles as $equipTitle) {
$titles .= [$equipTitle['equipment_category_id']=>$equipTitle['equipment_name']];
//echo $titles;
}
如果我将问题代码替换为实际的数组,它将按预期工作。
$titles = ["1"=>"Audio",
"2"=>"Video",
"3"=>"Lighting",
"4"=>"Other"];
代码段
function getEquipCat() {
global $db;
$query = "SELECT equipment_category_id, equipment_name
FROM equip_category ORDER BY equipment_category_id";
//lets prep to execute
$statement = $db->prepare($query);
$statement->execute();
$equipCat = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
return $equipCat;
}
.....
$equipTitles = getEquipCat();
.....
<?php
foreach ($equipTitles as $equipTitle) {
$titles .= [$equipTitle['equipment_category_id']=>$equipTitle['equipment_name']];
//echo $titles;
}
var_dump($titles);
?>
<?php foreach ($titles as $titleV => $title) :?>
<?php echo "<h4>$title</h4>";?>
<?php foreach ($allAudioEquipment[$titleV] as $audioEquipment) :?>
<div class="divTableBody">
<div class="divTableRow">
<div class="divTableCellEquipCode"><?php echo '<input type="hidden" id="'.$audioEquipment['equip_id'].'" name="equip_id" value="'.$audioEquipment['equip_id'].'">'.$audioEquipment['equip_id']; ?> </div>
<div class="divTableCellEquipDesc"><?php echo $audioEquipment['equip_name']; ?></div>
<div class="divTableCellEquipAdd"><input class="addToFlows" type="submit" value="+" /></div>
</div><!-- End Table Row -->
</div><!-- End Table Body -->
<?php endforeach; ?>
<?php endforeach; ?>
</div><!-- End Table -->
</div>
错误:未定义的变量:标题和注意:数组到字符串的转换
答案 0 :(得分:1)
.=
不是您添加到数组的方式,它用于追加到字符串。
使用
foreach ($equipTitles as $equipTitle) {
$titles[$equipTitle['equipment_category_id']] = $equipTitle['equipment_name'];
}
答案 1 :(得分:0)
我没有任何理由将您的结果集重新存储为第二个/冗余变量。只需在循环中使用结果集数据即可。
这将使您完全跳过脚本的foreach ($equipTitles as $equipTitle) {...}
部分-很好。
您的代码如下所示:
<?php
function getEquipCat($db) {
return $db->query("SELECT equipment_category_id,
equipment_name
FROM equip_category
ORDER BY equipment_category_id")
->fetchAll(PDO::FETCH_ASSOC);
}
foreach (getEquipCat($db) as $cat_row) {
echo "<h4>{$cat_row['equipment_name']}</h4>";
foreach ($allAudioEquipment[$cat_row['equipment_category_id']] as $audioEquipment) {
// ...
}
}
请注意,由于查询中没有要绑定的变量,因此我没有使用准备好的语句来查询数据库。如果您的项目在查询中使用变量,则保留准备好的语句语法。