[英]Building multidimensional arrays in PHP with foreach
How would I go about building output like this in PHP:我将如何在 PHP 中构建这样的输出:
$items[] = array(
'section_name' => 'Section 1 Name',
'items' => array(
array(
'item_name' => 'Item 1 Name - Section 1'
// there will be more in here
),
array(
'item_name' => 'Item 2 Name - Section 1'
// there will be more in here
)
)
);
$items[] = array(
'section_name' => 'Section 2 Name',
'items' => array(
array(
'item_name' => 'Item 1 Name - Section 2'
// there will be more in here
),
array(
'item_name' => 'Item 2 Name - Section 2'
// there will be more in here
)
)
);
// and so on
with this as the input以此作为输入
[section] => Array (
[0] => Array (
[name] => Section 1 Name
[item] => Array (
[0] => Array (
[name] => Item 1 Name - Section 1
// there will be more in here
)
[1] => Array (
[name] => Item 2 Name - Section 1
// there will be more in here
)
)
)
[1] => Array (
[name] => Section 2 Name
[item] => Array (
[0] => Array (
[name] => Item 1 Name - Section 2
// there will be more in here
)
)
)
)
There will never be a set number of items in a section and the number of sections will vary too so I need something iterative then a fixed number.一个部分中永远不会有固定数量的项目,并且部分的数量也会有所不同,所以我需要一些迭代的东西,然后是一个固定的数字。
Something like this ?像这样的东西? : :
$sections = [];
for ($sectionIndex = 0; $sectionIndex < 10; ++$sectionIndex) {
$items = [];
for ($itemIndex = 0; $itemIndex < 10; ++$itemIndex) {
$items[] = [
'item_name' => sprintf('Item %d Name - Section %d', $itemIndex, $sectionIndex);
];
}
$sections[] = [
'section_name' => sprintf("Section %d Name", $sectionIndex),
'items' => $items
];
}
Replace [] by array, since I don't know which PHP version you're using.将 [] 替换为数组,因为我不知道您使用的是哪个 PHP 版本。
Pass this your input array $section将此传递给您的输入数组 $section
$items=array();
$item=array();
foreach ($section as $row) {
$tmp=array();
$tmp['section_name']=$row['name'];
foreach($row['item'] as $key){
$item[]['item_name']=$key['name'];
}
$tmp['items']=$item;
$items[]=$tmp;
}
print_r($items);
Solved with a slightly modified version of the answer from @NoDataFound解决了@NoDataFound 答案的略微修改版本
$sections = [];
$s = 0;
foreach ($_POST['section'] as $section) {
$s++;
$items = [];
$i = 0;
foreach ($section['item'] as $item) {
$i++;
$items[] = [
'item_name' => sprintf('Item %d Name - Section %d', $i, $s)
];
}
$sections[] = [
'section_name' => sprintf("Section %d Name", $s),
'items' => $items
];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.