【问题标题】:how to add data to array using for loop in php?如何在php中使用for循环将数据添加到数组中?
【发布时间】:2013-04-25 21:23:45
【问题描述】:

我正在做一个 mysql 查询。我想将结果添加到数组中。假设我从用户表中选择所有用户。我想知道每个人的名字。如果 row=5 我想根据行索引保存每个名称。

if (mysql_num_rows($query) > 0)  
    {  
        $row = mysql_fetch_array($query);
        //echo ($row);
         $num=mysql_num_rows($query);
        echo ($num);
        for ($i=1; $i<=$num;$i++){

        //here I want to save all name to an array.              

        }

请帮忙。

【问题讨论】:

  • 阅读网络上的任何基本 PHP MySQL 教程。这是非常基本的事情。

标签: php database arrays for-loop


【解决方案1】:

您可能正在寻找这样的东西:

$rows = array();
// while there are more records, add them to `$rows`
while($row = mysql_fetch_assoc($result)) {
    $rows []= $row;
}

请注意,如果结果集中没有(更多)记录,mysql_fetch_assoc() 只会返回 false。所以你不需要打电话给mysql_num_rows()

【讨论】:

    【解决方案2】:
    $num = mysql_num_rows($query);
    
    if($num > 0)
    {
        while($row = mysql_fetch_array($query)
        {
            $names[] = $row['name'];
        }
    }
    

    这将创建一个名为 $names 的数组,您可以稍后循环访问该数组。此外,现在是研究 mysqli_* 函数或 PDO 的好时机。

    【讨论】:

      猜你喜欢
      • 2016-01-16
      • 1970-01-01
      • 2020-10-22
      • 1970-01-01
      • 2013-04-09
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      • 2013-07-25
      相关资源
      最近更新 更多