PHP如何生成动态列表()? [英] php how to generate dynamic list()?

查看:390
本文介绍了PHP如何生成动态列表()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的理解,list()的工作原理.

base on my understanding, this how list() work.

list($A1,$A2,$A3) = array($B1,B2,B3);

因此,在list()的帮助下,我们可以从数组中相应地分配值.
这是我的问题... 如何生成动态列表()?

So with the help of list() we can assign value out from array accordingly.
here is my question... how to generate a dynamic list()?

1).根据数据库的返回结果,我不确定有多少,但是我将它们全部分配给了数组
2).因此我们可以使用count(array)来知道其中有多少.
3).因此,我如何生成/复制列表?

1). base on database return result, I'm not sure how many of it but I assign it all into array
2). so we can use count(array) to know how many of it.
3). so then HOW CAN I GENERATE/PREPARE a list for it?

示例:客户A,有3个孩子,名字为Apple,Boy,Cat 所以我用list($kid1, $kid2, $kid3)来实现.

Example: client A, have 3 kids, name Apple, Boy, Cat so I use list($kid1, $kid2, $kid3) for it.

但是当客户B的孩子超过3个时,我只会得到前3个孩子 或如果客户C只有一个孩子,那么就会遇到错误.

but when client B, have more then 3 kids, I only get first 3 or if client C, have only 1 kids, then error encounter.

我知道是否基于上述情况,有很多方法可以解决,而无需使用list() 但是我想使用list()来了解或找出解决方案.

I know if base on the situation above, there is many way to solve it without using list() but I wish to know or find out the solution with using list().

如何基于array()

How to generate dynamic list() base on count of array()

感谢男生/女友

推荐答案

如果元素数量可变,请对它们使用 array !如果您不知道将要处理多少个变量,则将它们提取为单个变量是没有意义的.假设您确实将这些值提取到变量$kid1$kidN中,那么此后的代码是做什么的?您现在不知道范围中有多少个变量,也没有在测试$kid1$kidN是否为isset旁边找出或迭代它们的实用方法.这是对变量的疯狂使用.只需使用数组即可.

If you have a variable number of elements, use arrays for them! It does not make sense to extract them into individual variables if you do not know how many variables you'll be dealing with. Say you did extract those values into variables $kid1 through $kidN, what is the code following this going to do? You have no idea how many variables there are in the scope now, and you have no practical method of finding out or iterating them next to testing whether $kid1 through $kidN are isset or not. That's insane use of variables. Just use arrays.

话虽如此,变量变量:

$i = 1;
foreach ($array as $value) {
    $varname = 'kid' . $i++;
    $$varname = $value;
}

这篇关于PHP如何生成动态列表()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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