使用foreach循环创建多维数组

时间:2013-08-08 20:39:18

标签: php multidimensional-array

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

如何修改代码以实现目标?

3 个答案:

答案 0 :(得分:11)

你到处都是。只需将级别添加到数组创建中:)

$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
        )

)

答案 1 :(得分:4)

<?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);

答案 2 :(得分:1)

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

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