【问题标题】:array_push mysqli $row return the same dataarray_push mysqli $row 返回相同的数据
【发布时间】:2015-03-20 15:00:28
【问题描述】:

我有一个这样的数据库返回数组

$row['id']=1, $row['col1']='col1', $row['col2']=col2 

当我将每个 $row 推送到 $result 时

array_push($result, $row); 

$row 被覆盖 b/c 他们共享相同的密钥。我想不通。但如果它被覆盖,当我 var_dump($result) 时它应该只输出一组,而不是输出具有相同数据集的多行,请帮助。

【问题讨论】:

  • 正如上面的代码所示,您将整个 $row 数组推送到 $result 数组...
  • 您阅读手册了吗? array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed.

标签: php arrays mysqli


【解决方案1】:

替换这个:array_push($result, $row); 用这个:

foreach($row AS $current_row)
{
   array_push($result, $current_row);
}

【讨论】:

    【解决方案2】:

    我不确定。
    如果你想在$result中添加$row,你可以像这样使用array_merge()函数:

    $result = array_merge($result, $row);
    

    【讨论】:

    • 这也可以,但@milk 允许更好的数组结构。谢谢
    • 感谢您的回归和支持。 :) 祝你好运。
    【解决方案3】:

    array_push 将元素添加到 2 维或更多维数组。在使用它之前,您必须定义一个数组。使用这个:

    $result = array();
    while ($row = $stmt->fetch())
    {
       array_push($result, $row);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-05
      • 2016-07-09
      • 2014-08-28
      • 1970-01-01
      • 2012-11-02
      • 2015-10-29
      • 2017-04-03
      • 1970-01-01
      相关资源
      最近更新 更多