[英]add items to multidimensional array programmatically in php
我有以下数组
$a = array(0 => 'Item',
1 => 'Wattles',
2 => 'Types',
3 => 'Compost',
4=> 'Estimated',
5 => '123',
6 => 'Actual',
7 => '12',
);
用以下代码排序。
echo "<pre>";
print_r($a);
$a_len = count($a);
$fnl = array();
$i = 0;
while($i<$a_len){
$fnl[$a[$i]] = $a[++$i];
$i++;
}
print_r($fnl);
正确打印
Array
(
[Item] => Wattles
[Types] => Compost
[Estimated Qty] => 123
[Actual Qty] => 12
)
直到我添加多个条目。
Array
(
[0] => Item
[1] => Wattles
[2] => Types
[3] => Compost
[4] => Estimated Qty
[5] => 123
[6] => Actual Qty
[7] => 12
[8] => Item
[9] => Silt Fence
[10] => Types
[11] => Straw
[12] => Estimated Qty
[13] => 45
[14] => Actual Qty
[15] => 142
)
我需要在多维数组中进行添加。
$items = array
(
array("Wattles","Silt Fence), //items
array("Compost","Straw"), //types
array(123,45), //estimated quantity
array(12,142) //actual quantity
);
有一些给定的数字。 列表重复之前,恰好有4个条目(8个项目)。
我已经在这部分上停留了几个小时,并且不知道如何使我的代码正常工作。
要使用字符串键获得预期的结果,您可以执行以下操作:
foreach(array_chunk($a, 2) as $pairs) {
$result[$pairs[0]][] = $pairs[1];
}
产量:
Array
(
[Item] => Array
(
[0] => Wattles
[1] => Silt Fence
)
[Types] => Array
(
[0] => Compost
[1] => Straw
)
[Estimated] => Array
(
[0] => 123
[1] => 45
)
[Actual] => Array
(
[0] => 12
[1] => 142
)
)
然后,如果要对其进行数字索引:
$result = array_values($result);
您的多维数组结构错误。 您应该像这样构造数组:
$a = array(
0 => array(
'Item' => 'Wattles',
'Types' => 'Compost',
'Estimated' => 123,
'Actual' => 12
)
);
然后添加到它:
$a[] = array(
'Item' => 'Silt Fence',
'Types' => 'Straw',
'Estimated' => 45,
'Actual' => 142
);
渲染出来以查看结果,这正是我认为您想要的。
print_r($a);
如果您想了解如何根据需要按子数组值对多维数组进行排序,我可以发布一个链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.