How would I go about building output like this in 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.
Pass this your input array $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
$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
];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.