create multidimensional array using a foreach loop(使用 foreach 循环创建多维数组)
本文介绍了使用 foreach 循环创建多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 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 .'_' .$级别;Endforeach;Endforeach;echo ''.print_r($levels,1) .'</pre>';echo ''.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 .'_' .$级别;//将 $variables[] 改为 $variables[$level][]Endforeach;Endforeach;echo ''.print_r($levels,1) .'</pre>';echo ''.print_r($variables,1) .'</pre>';
输出
数组([低] =>大批([0] =>脂肪_低[1] =>数量_低[2] =>比率_低[3] =>标签低)[中] =>大批([0] =>肥中[1] =>数量_中等[2] =>比率_中[3] =>label_medium)[高] =>大批([0] =>脂肪高[1] =>数量_高[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
)
)
这篇关于使用 foreach 循环创建多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:使用 foreach 循环创建多维数组
基础教程推荐
猜你喜欢
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01