php 使用 foreach 循环创建多维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18135685/
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
create multidimensional array using a foreach loop
提问by knot22
I am trying to create a multidimensional array in PHP using a foreach loop. Here is the code thus far:
我正在尝试使用 foreach 循环在 PHP 中创建一个多维数组。这是迄今为止的代码:
$levels = array('low', 'medium', 'high');
$attributes = array('fat', 'quantity', 'ratio', 'label');
foreach ($levels as $key => $level):
foreach ($attributes as $k =>$attribute):
$variables[] = $attribute . '_' . $level;
endforeach;
endforeach;
echo '<pre>' . print_r($levels,1) . '</pre>';
echo '<pre>' . print_r($variables,1) . '</pre>';
The output from this code is a single dimension array; however, that is not the intent. The desired array should look like this:
此代码的输出是一维数组;然而,这不是本意。所需的数组应如下所示:
How should the code be modified to achieve the goal?
应该如何修改代码才能达到目的?
回答by JimL
You're aaalmost there. Just add the level to the array creation :)
你快到了。只需将级别添加到数组创建中:)
$levels = array('low', 'medium', 'high');
$attributes = array('fat', 'quantity', 'ratio', 'label');
foreach ($levels as $key => $level):
foreach ($attributes as $k =>$attribute):
$variables[$level][] = $attribute . '_' . $level; // changed $variables[] to $variables[$level][]
endforeach;
endforeach;
echo '<pre>' . print_r($levels,1) . '</pre>';
echo '<pre>' . print_r($variables,1) . '</pre>';
Output
输出
Array
(
[low] => Array
(
[0] => fat_low
[1] => quantity_low
[2] => ratio_low
[3] => label_low
)
[medium] => Array
(
[0] => fat_medium
[1] => quantity_medium
[2] => ratio_medium
[3] => label_medium
)
[high] => Array
(
[0] => fat_high
[1] => quantity_high
[2] => ratio_high
[3] => label_high
)
)
回答by Tomasz Kowalczyk
<?php
$levels = array('low', 'medium', 'high');
$attributes = array('fat', 'quantity', 'ratio', 'label');
$ret = array();
foreach ($levels as $level) {
$ret[$level] = array();
foreach($attributes as $attribute) {
$ret[$level][] = $attribute.'_'.$level;
}
}
var_dump($ret);
回答by Tomasz Kowalczyk
$levels = array('low', 'medium', 'high');
$attributes = array('fat', 'quantity', 'ratio', 'label');
foreach ($levels as $key => $level){
foreach ($attributes as $k =>$attribute){
$variables[$level][] = $attribute . '_' . $level;
}
}
print_r($variables);