Php 无法用sql行填充多维数组
我目前无法将单个行保存到多维数组中。下面的当前代码(php)不会创建多维数组,即使$Prow本身应该是数组。代码末尾的echo不返回任何值,是否有帮助? 编辑:ps,查询工作正常Php 无法用sql行填充多维数组,php,sql,arrays,multidimensional-array,Php,Sql,Arrays,Multidimensional Array,我目前无法将单个行保存到多维数组中。下面的当前代码(php)不会创建多维数组,即使$Prow本身应该是数组。代码末尾的echo不返回任何值,是否有帮助? 编辑:ps,查询工作正常 $sql = "SELECT * FROM Products WHERE Tags LIKE '%atmega%'"; $result = $conn->query($sql); $xx = 0; while($Prow = $result->fetch_assoc()){ $PArray[$xx]
$sql = "SELECT * FROM Products WHERE Tags LIKE '%atmega%'";
$result = $conn->query($sql);
$xx = 0;
while($Prow = $result->fetch_assoc()){
$PArray[$xx] = $Prow;
$xx += 1;
}
echo "<script type='text/javascript'>alert('".$PArray[0][0]."');</script>";
$sql=“从带有“%atmega%”等标记的产品中选择*;
$result=$conn->query($sql);
$xx=0;
而($Prow=$result->fetch_assoc()){
$PArray[$xx]=$Prow;
$xx+=1;
}
回显“警报('”$PArray[0][0]。');”;
假设mysqli
,$result->fetch_assoc()
返回关联数组,而不是零索引数组。索引是您的列标题。如果需要枚举数组,请尝试使用$result->fetch_row()
。如果想知道数组的外观,请对其执行打印()
哦,在调用->query()
为了简化您的代码,您可以这样做
$sql = "SELECT * FROM Products WHERE Tags LIKE '%atmega%'";
$result = $conn->query($sql);
if ( $result === FALSE ) {
echo $conn->error;
exit;
}
while($row = $result->fetch_assoc()){
$PArray[] = $row;
}
print_r($PArray);
但是要在返回的数组而不是关联数组上获取数字索引,请使用->fetch_row()
主要问题见Ray的答案。旁注:不需要使用$xx
增加数组索引:只需使用:$PArray=array();而(…)$PArray[]=$PRow代码>为什么您认为它不是多维数组?是的,但第二维度的索引是列名,而不是数字。例如,请尝试使用$PArray[0]['id']
。Barmar谢谢!我希望我能接受你的评论作为我的答案,但不幸的是我不能。它工作得很好。
$sql = "SELECT * FROM Products WHERE Tags LIKE '%atmega%'";
$result = $conn->query($sql);
if ( $result === FALSE ) {
echo $conn->error;
exit;
}
while($row = $result->fetch_assoc()){
$PArray[] = $row;
}
print_r($PArray);
$sql = "SELECT * FROM Products WHERE Tags LIKE '%atmega%'";
$result = $conn->query($sql);
if ( $result === FALSE ) {
echo $conn->error;
exit;
}
while($row = $result->fetch_row()){
$PArray[] = $row;
}
print_r($PArray);