簡體   English   中英

使用 foreach 循環創建多維數組

[英]create multidimensional array using a foreach loop

我正在嘗試使用 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>';    

此代碼的輸出是一維數組; 然而,這不是本意。 所需的數組應如下所示:

輸出目標

應該如何修改代碼才能達到目的?

你快到了。 只需將級別添加到數組創建中:)

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM