【问题标题】:Unable to Fill multidimensional arrays with sql rows无法用 sql 行填充多维数组
【发布时间】:2016-02-16 22:31:51
【问题描述】:

我目前无法将单个行保存到多维数组中。下面的当前代码 (php) 不会创建多维数组,即使 $Prow 本身应该是一个数组。代码末尾的回显不返回任何值,有帮助吗? 编辑:ps,查询完美。

$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>";

【问题讨论】:

  • 查看 Ray 的主要问题答案。旁注:您不需要使用$xx 增加数组索引:您可以简单地使用:$PArray = array(); while(...) $PArray[] = $PRow;
  • 为什么你认为它不是多维数组?是的,但是第二维的索引是列名,而不是数字。
  • 试试$PArray[0]['id'],例如。
  • 巴尔玛谢谢!我希望我能接受你的评论作为我的回答,但不幸的是我不能。效果很好。

标签: php sql arrays multidimensional-array


【解决方案1】:

如果您想知道您的阵列是什么样的,请在其上执行print_r()

哦,您应该在致电 -&gt;query() 后检查错误

$sql = "SELECT * FROM Products WHERE Tags LIKE '%atmega%'"; 
$result = $conn->query($sql);
if ( $result === FALSE ) {
    echo $conn->error;
    exit;
}
$xx = 0;

while($Prow = $result->fetch_assoc()){ 
   $PArray[$xx] = $Prow;
   $xx += 1;
}
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_assoc()){ 
   $PArray[] = $row;
}
print_r($PArray);

但是要获得返回数组的数字索引而不是关联数组,请使用-&gt;fetch_row()

$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);

【讨论】:

    【解决方案2】:

    假设mysqli$result-&gt;fetch_assoc() 返回一个关联数组,而不是零索引数组。索引是您的列标题。如果你想要一个枚举数组,试试$result-&gt;fetch_row()

    【讨论】:

      猜你喜欢
      • 2015-10-23
      • 1970-01-01
      • 2011-01-11
      • 1970-01-01
      • 2023-03-25
      • 2013-02-20
      • 1970-01-01
      相关资源
      最近更新 更多