如何从foreach循环输出中分配PHP变量? [英] How to assign PHP variables from foreach loop output?

查看:174
本文介绍了如何从foreach循环输出中分配PHP变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个foreach循环,它打印出数据库表中所有条目的用户名,如下所示:

I have a foreach loop which prints out the usernames of all entries in a database table like so:

foreach($results as $result){

echo $result->username;
echo '<br>';

}

随着越来越多的用户被添加到表中,列表将不断增长.我想列出完整的列表,并将每个条目分配给一个单独的PHP变量,以供以后在PHP脚本中使用.最好的方法是什么?

As more and more users are added to the table, the list will grow. I would like to take the complete list and assign each entry to a separate PHP variable for use later on the PHP script. What is the best way to do this?

推荐答案

您不希望使用单个变量,请尝试使用数组:

You don't want individual variables, try an array:

foreach($results as $result){
    $names[] = $result->username;
}

在PHP 7中,它甚至更容易:

In PHP 7 it's even easier:

$names = array_column($results, null, 'username');

这篇关于如何从foreach循环输出中分配PHP变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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