簡體   English   中英

合並兩個php數組(或多個)到一個表

[英]Merge two php arrays (or more) to one table

我有2個數組:

數組1包含2個產品。

[records] => Array
        (
            [0] => Array
                (
                    [productID] => 3347
                    [amountInStock] => 2.000000
                )

            [1] => Array
                (
                    [productID] => 6798
                    [amountInStock] => 1.000000
                )
    )

數組2包含3個產品。 一種產品也在陣列中

[records] => Array
        (
            [0] => Array
                (
                    [productID] => 3347
                    [amountInStock] => 0
                )

            [1] => Array
                (
                    [productID] => 6332
                    [amountInStock] => 1.000000
                )
        [2] => Array
                (
                    [productID] => 6922
                    [amountInStock] => 3.000000
                )
    )

現在我需要像這樣將2個數組合並到表中

product | array 1   |  array 2

3347      2            0
6798      1            0
6332      0            0
6922      0            2

我該怎么辦

使用foreach並將元素添加到新數組。

$new = [];

foreach ($array1 as $element) {
   if (isset($new[$element['productID']])) {
       $new[$element['productID']]['array 1'] = $element['ammountInStock'];
   } else {
       $new[$element['productID']]['array 1'] = $element['ammountInStock'];
       $new[$element['productID']]['array 2'] = 0;
   }
}

foreach ($array1 as $element) {
   if (isset($new[$element['productID']])) {
       $new[$element['productID']]['array 2'] = $element['ammountInStock'];
   } else {
       $new[$element['productID']]['array 2'] = $element['ammountInStock'];
       $new[$element['productID']]['array 1'] = 0;
   }
}

完成您正在尋找的內容的另一種方法是使用array_merge()

<?php
$arr1 = array(
          array('productID' => 3347,
                'amountInStock' => 2.000000
                ),
          array('productID' => 6798,
                'amountInStock' => 1.000000
                )
        );

$arr2 = array(
          array('productID' => 6332,
                'amountInStock' => 3.000000
                ),
          array('productID' => 6330,
                'amountInStock' => 4.000000
                )
        );

$arr = array_merge($arr1, $arr2);

var_dump($arr);
?>

演示: https : //eval.in/205237

編輯:如果要防止重復的條目,請嘗試也使用array_unique()

演示: https : //eval.in/205238

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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