使用嵌套循环,使用关联的第一级键和来自两个平面数组的索引行元素填充二维数组

问题描述 投票:0回答:3

我正在尝试使用 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>';    

这段代码的输出是一个一维数组;然而,这不是目的。所需的数组应如下所示:

OutputGoal

代码应该如何修改才能达到目的?

php arrays loops multidimensional-array associative-array
3个回答
16
投票

你就快到了。只需将级别添加到数组创建中即可:)

$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>';  

输出

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
        )

)

6
投票
$levels = ['low', 'medium', 'high'];
$attributes = ['fat', 'quantity', 'ratio', 'label'];

$result = [];
foreach ($levels as $level) {
    $result[$level] = [];
    foreach ($attributes as $attribute) {
        $result[$level][] = $attribute . '_' . $level;
    }
}

var_dump($result);

1
投票
$levels = ['low', 'medium', 'high'];
$attributes = ['fat', 'quantity', 'ratio', 'label'];

foreach ($levels as $level) {
    foreach ($attributes as $attribute) {
        $variables[$level][] = $attribute . '_' . $level;
   }
}

print_r($variables);

http://codepad.viper-7.com/xlvZ2W

© www.soinside.com 2019 - 2024. All rights reserved.