【发布时间】:2011-12-09 17:17:54
【问题描述】:
我有一个(动态)数组,在本例中包含 4 组数据(每组 5 个字段),但它可能只有一组或最多 25 组。
Array ( [lightwattage1] => 50 [lightvoltage1] => 12 [lightquantity1] => 2 [lightusage1] => 4 [lightcomment1] => [lightwattage2] => 60 [lightvoltage2] => 24 [lightquantity2] => 4 [lightusage2] => 5 [lightcomment2] => [lightwattage3] => 30 [lightvoltage3] => 240 [lightquantity3] => 4 [lightusage3] => 2 [lightcomment3] => [lightwattage4] => 25 [lightvoltage4] => 12 [lightquantity4] => 2 [lightusage4] => 6 [lightcomment4] => )
我想把它变成类似的东西
Array ( Array ( [lightwattage1] => 50 [lightvoltage1] => 12 [lightquantity1] => 2 [lightusage1] => 4 [lightcomment1] => ),
Array ( [lightwattage2] => 60 [lightvoltage2] => 24 [lightquantity2] => 4 [lightusage2] => 5 [lightcomment2] => ),
Array ( [lightwattage3] => 30 [lightvoltage3] => 240 [lightquantity3] => 4 [lightusage3] => 2 [lightcomment3] => ),
Array ( [lightwattage4] => 25 [lightvoltage4] => 12 [lightquantity4] => 2 [lightusage4] => 6 [lightcomment4] => )
)
原始数组是这样创建的:
$light = Array();
foreach( $_POST as $key => $val )
{
//field names that start with light to go in this array
if (strpos($key, 'light') === 0) {
$light[$key] = $val;
}
}
字段名称数字是在提交表单之前已经用JS添加的,而不是通过php脚本添加的。 非常感谢任何提示。
【问题讨论】:
-
遍历原始数组,当您看到已经设置了一个键时,您就会知道是时候开始将数据放入新的子数组中了。
标签: php arrays loops multidimensional-array