簡體   English   中英

使用 foreach 在 PHP 中構建多維數組

[英]Building multidimensional arrays in PHP with foreach

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

       )
   )

)

一個部分中永遠不會有固定數量的項目,並且部分的數量也會有所不同,所以我需要一些迭代的東西,然后是一個固定的數字。

像這樣的東西?

$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 版本。

將此傳遞給您的輸入數組 $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);

解決了@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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM