本文介紹了使用 foreach 循環(huán)創(chuàng)建多維數(shù)組的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試使用 foreach 循環(huán)在 PHP 中創(chuàng)建一個多維數(shù)組.這是目前為止的代碼:
$levels = array('low', 'medium', 'high');$attributes = array('fat', 'quantity', 'ratio', 'label');foreach ($levels as $key => $level):foreach ($attributes as $k =>$attribute):$variables[] = $attribute .'_' .$級別;Endforeach;Endforeach;echo ''.print_r($levels,1) .'</pre>';echo ''.print_r($variables,1) .'</pre>';
這段代碼的輸出是一個一維數(shù)組;然而,這不是本意.所需的數(shù)組應如下所示:
應該如何修改代碼才能達到目標?
解決方案
您就快到了.只需將級別添加到數(shù)組創(chuàng)建中:)
$levels = array('low', 'medium', 'high');$attributes = array('fat', 'quantity', 'ratio', 'label');foreach ($levels as $key => $level):foreach ($attributes as $k =>$attribute):$variables[$level][] = $attribute .'_' .$級別;//將 $variables[] 改為 $variables[$level][]Endforeach;Endforeach;echo ''.print_r($levels,1) .'</pre>';echo ''.print_r($variables,1) .'</pre>';
輸出
數(shù)組([低] =>大批([0] =>脂肪_低[1] =>數(shù)量_低[2] =>比率_低[3] =>標簽低)[中] =>大批([0] =>肥中[1] =>數(shù)量_中等[2] =>比率_中[3] =>label_medium)[高] =>大批([0] =>脂肪高[1] =>數(shù)量_高[2] =>比率_高[3] =>標簽高))
I am trying to create a multidimensional array in PHP using a foreach loop. Here is the code thus far:
$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?
解決方案
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
)
)
這篇關(guān)于使用 foreach 循環(huán)創(chuàng)建多維數(shù)組的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!