簡體   English   中英

在php中以編程方式將項目添加到多維數組

[英]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.

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