循环遍历 mysql 查询结果集时填充包含两个元素行的数组
我有一个二维数组,我想用 while 循环将值推送给它;
$arr[0][1] = 1. value
$arr[0][2] = 2. value
我已经尝试过
while ($zRow = mysql_fetch_array($zQuery))
{
$props[]['name'] = $zRow['name'];
$props[]['photo'] = $zRow['thumbnail'];
}
这个循环将名称推送到 $props[0][name] 并将缩略图推送到 $props[1][photo]
我也尝试过
$j = 0;
while($zRow = mysql_fetch_array($zQuery))
{
$props[$j]['name'] =$zRow['name'];
$props[$j]['photo'] =$zRow['thumbnail'];
$j += 1;
}
这有效,但是有了这个,当我稍后使用 foreach 循环时,它会带来像“非法”这样的麻烦偏移类型”。
这是我的 foreach 循环:
foreach ($props as $no)
{
echo $props[$no]['name'];
}
现在我的问题是:
- 除了使用
$j
变量(例如用于二维数组的array_push()
)的 while 循环之外,还有其他方法吗? - 如何对二维数组使用 foreach 循环?
I've a 2-dimensional array and i want to push values to it with a while loop like;
$arr[0][1] = 1. value
$arr[0][2] = 2. value
I've tried
while ($zRow = mysql_fetch_array($zQuery))
{
$props[]['name'] = $zRow['name'];
$props[]['photo'] = $zRow['thumbnail'];
}
This loop pushes name to $props[0][name] and thumbnail to $props[1][photo]
I also tried
$j = 0;
while($zRow = mysql_fetch_array($zQuery))
{
$props[$j]['name'] =$zRow['name'];
$props[$j]['photo'] =$zRow['thumbnail'];
$j += 1;
}
That works but with this I when I use foreach loop later, it makes trouble like "Illegal offset type".
Here is my foreach loop:
foreach ($props as $no)
{
echo $props[$no]['name'];
}
Now my questions:
- Are there any other way than while loop with
$j
variable likearray_push()
for 2-dimensional arrays? - How can I use foreach loop for 2-dimensional arrays?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将第一个循环更改为以下内容:
您的方法也有效,但您需要额外的变量。
在第二个循环中,您实际需要做的是:
You could change the first loop to the following:
Your method also works, but you need that extra variable.
In your second loop, what you actually need to be doing is:
使用
$myArray[] = 'foo'
将任何内容推入数组都会增加数组的计数器。对于多维数组,您需要填充“内部”数组,然后将其推送到“外部”(在您的情况下为
$props
)数组。要迭代深度已知的多维数组:
如果嵌套深度未知,您可能必须使用递归函数来收集数据。
Pushing anything onto an array with
$myArray[] = 'foo'
will increment the array's counter.For multidimensional array, you need to populate the "inner" array, then push it to the "outer" (in your case
$props
) array.To iterate over multidimensional arrays whose depth is known:
If the depth of the nesting is not known, you may have to use a recursive function to gather the data.