Php 将值推送到二维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9153444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Php pushing values to a 2-dimensional array
提问by Malixxl
i've a 2-dimensional array and i want to push values to it with a while loop like;
我有一个二维数组,我想用 while 循环将值推送给它;
$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]
此循环将名称推送到 $props[0][name] 并将缩略图推送到 $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"
这可行,但是当我稍后使用 foreach 循环时,它会产生“非法偏移类型”之类的麻烦
and here is my foreach loop
这是我的 foreach 循环
foreach($props as $no)
{
echo $props[$no]['name'];
}
now my questions; 1) are there any other way than while loop with $j variable like array_push for 2-dimensional arrays 2)how can i use foreach loop for 2-dimensional arrays
现在我的问题;1) 除了带有 $j 变量的 while 循环之外还有其他方法,例如用于二维数组的 array_push 2) 我如何将 foreach 循环用于二维数组
回答by drew010
You could change the first loop to the following:
您可以将第一个循环更改为以下内容:
while($zRow = mysql_fetch_array($zQuery))
{
$row = array();
$row['name'] = $zRow['name'];
$row['photo'] = $zRow['thumbnail'];
$props[] = $row;
}
Your method also works, but you need that extra variable.
您的方法也有效,但您需要额外的变量。
In your second loop, what you actually need to be doing is:
在您的第二个循环中,您实际需要做的是:
foreach($props as $index => $array)
{
echo $props[$index]['name'];
// OR
echo $array['name'];
}
回答by Andy
Pushing anything onto an array with $myArray[] = 'foo'
will increment the array's counter.
将任何内容推送到数组上$myArray[] = 'foo'
都会增加数组的计数器。
For multidimensional array, you need to populate the "inner" array, then push it to the "outer" (in your case $props
) array.
对于多维数组,您需要填充“内部”数组,然后将其推送到“外部”(在您的情况下$props
)数组。
while($zRow = mysql_fetch_array($zQuery)) {
$data = array('name' => $zRow['name'], 'photo' => $zRow['thumbnail']);
$props[] = $data;
}
To iterate over multidimensional arrays whose depth is known:
迭代深度已知的多维数组:
foreach ($props as $prop) {
foreach ($prop as $key => $value) {
echo "{$key} => {$value}" . PHP_EOL;
}
}
If the depth of the nesting is not known, you may have to use a recursive function to gather the data.
如果嵌套的深度未知,您可能必须使用递归函数来收集数据。