【问题标题】:PHP: print all the items of an array [duplicate]PHP:打印数组的所有项目[重复]
【发布时间】:2020-09-29 15:45:26
【问题描述】:

我的目标:将来自查询的项目数组插入到变量中,然后打印出来

步骤:

  1. 启动查询
  2. 用php做点什么
  3. 打印变量$report = 'this is your list: $list';

试过这个:


    $myquery = mysqli_query($dbconnection, "SELECT ...");

    while($row = mysqli_fetch_assoc($myquery)) {
      $my_array = $row['field'];
      echo "$my_array, "; /* here I've the full list*/
    }

    $report = 'this is your list:' .$my_array. '.';

    echo "$report"; /*I've only one item and not all the list*/

【问题讨论】:

  • 所有基本问题都已经回答了好几次。在发布新问题之前,请通过搜索 Stackoverflow 来享受丰富的现有知识。
  • 谢谢。我达到了我的目标,而不是使用 php,而只是在 mysql 查询中添加一个“GROUP_CONCAT”

标签: php mysql arrays


【解决方案1】:

您的第一个echo 被多次调用,因为它在循环中。 在每次迭代中,您都在替换 $my_array 的内容。

相反,尝试附加它:

$my_array[] = $row['field'];

欲了解更多信息,请参阅https://www.php.net/manual/de/language.types.array.php

【讨论】:

  • 然后 echo "$report"; 会报错。
  • 你是对的。您不能回显数组。改用var_dump
【解决方案2】:

这是正常的。 您的 while 循环为您的查询找到的每一行执行一个“步骤”。 您将 $my_array 分配为名称为 field 的“列”。

所以在while 循环结束时,您将只获得最后一行的最后一列field

试试这个

$myquery = mysqli_query($dbconnection, "SELECT ...");
$myWholeList = ''; // HERE

while($row = mysqli_fetch_assoc($myquery)) {
    $my_array = $row['field'];
    echo "$my_array, ";
    $myWholeList .= '$my_array '; // HERE
}

$report = 'this is your list:' .$my_array. '.';
echo "$myWholeList"; // HERE

我已经完成了字符串连接,但是您可以使用数组和print_r() 函数来完成。查看此线程以了解如何将数据附加到数组。

mysqli_fetch_array while loop columns

编辑: 根据@isabella 的评论,她想显示 7 项数组。

两种方式:

  • 使用print_r()var_dump() 最适合显示数组(无需考虑渲染)

  • 将每个项目添加到$myWholeList 变量中。

例如

$myquery = mysqli_query($dbconnection, "SELECT ...");
$myWholeList = ''; // HERE

while($row = mysqli_fetch_assoc($myquery)) {
    $my_array = $row['field'];
    echo "$my_array, ";

    // HERE
    foreach($row as $field) {
        $myWholeList .= $field . ' ';
    }
    $myWholeList .= '<br>'; // NEW LINE
}

$report = 'this is your list:' .$my_array. '.';
echo "$myWholeList"; // HERE

【讨论】:

  • 感谢您的回复:我试过了,但是当我打印 $myWholeList 变量时,它会打印字符串 $my_array 的 7 倍,而不是打印数组的 7 项...
  • @isabella 我只是添加了一些关于您的请求的解释;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-26
  • 2015-08-03
  • 1970-01-01
  • 2014-05-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多