PHP数组:结果集中的内容 [英] PHP Array: Contents from result set

查看:86
本文介绍了PHP数组:结果集中的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当简单的问题,但我一直无法找到解决方案.我想用mySQL列的内容填充数组.

I have a fairly simple problem to which I've been unable to find a solution. I'd like to fill an array with the contents of a mySQL column.

基本上,我有一个收集结果集的循环,我需要从该结果集中提取特定列并将其放入数组中.

Basically I have a loop that gathers the result set, and I need to take a specific column from this result set and put it into an array.

    foreach ($results as $row){

      $names = array();

      $names[] = $row['name'];

    };

假设结果集中有40个名字,它们现在都应该放在$ names数组中,但是当我尝试在屏幕上打印内容时,我只会得到最后一个结果:

Let's say there were 40 names in the result set they should now all be in the $names array, but I only get the last result when I attempt to print the contents on screen:

    echo $names[0]; or print_r($names);

我也尝试过:

    while($row = mysql_fetch_array($results)) {

       $names[] = $row['name']; 

    }

但是我已经有了foreach的设置并且可以正常工作,所以我不想引入另一个循环来填充数组.

However I already have the foreach setup and working so I don't want to introduce another loop just to populate the array.

我知道查询和循环都可以正常工作,因为我可以通过放置以下内容直接回显每个名称的值:

I know the query and loop are both working because I can echo out the value of each name directly by placing:

    echo $row['name'] 

在循环中,然后看到结果名称显示在屏幕上.

in the loop and see the resulting names print on screen.

推荐答案

尝试

$names = array();
foreach ($results as $row){
      $names[] = $row['name'];
}

您要在每个循环中将$names重新声明为空白数组,以删除添加到其中的项目.

You were re-declaring $names to a blank array on each loop removing the item you added to it.

这篇关于PHP数组:结果集中的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆