使用foreach在PHP中构建多维数组

时间:2014-08-10 14:01:56

标签: php arrays

我如何在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

以此为输入

[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
            )

       )
   )

)

一个部分中永远不会有一定数量的项目,而且部分的数量也会有所不同,所以我需要一些迭代的东西,然后是一个固定的数字。

3 个答案:

答案 0 :(得分:1)

这样的东西? :

$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
  ];
}

用数组替换[],因为我不知道你正在使用哪个PHP版本。

答案 1 :(得分:1)

传递你的输入数组$ 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);

答案 2 :(得分:0)

使用@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
        ];
    }