簡體   English   中英

按日期合並數組和重新分組數據

[英]Merge array and regroup data by date

我有兩個多維數組,並希望盡可能按日期對數據進行分組(在 php 中)。 我嘗試使用 merge 和 merge_recursive 但它不起作用。

第一個數組:

array(100) {
  [1]=>
  array(1) {
    ["2020-04-18"]=>
    array(1) {
      ["best_price_product"]=>
      float(489.1)
    }
  }
  [2]=>
  array(1) {
    ["2020-04-19"]=>
    array(1) {
      ["best_price_product"]=>
      float(489.1)
    }
  }
  [3]=>
  array(1) {
    ["2020-04-20"]=>
    array(1) {
      ["best_price_product"]=>
      float(489.1)
    }
  }
  [4]=>
  array(1) {
    ["2020-04-21"]=>
    array(1) {
      ["best_price_product"]=>
      float(489.1)
    }
  }
  ….
  }
  

第二個數組:

  array(88) {
  [1]=>
  array(1) {
    ["2020-04-18"]=>
    array(1) {
      ["best_price_product_mp"]=>
      float(526.3)
    }
  }
  [2]=>
  array(1) {
    ["2020-04-19"]=>
    array(1) {
      ["best_price_product_mp"]=>
      float(526.3)
    }
  }
  [3]=>
  array(1) {
    ["2020-04-20"]=>
    array(1) {
      ["best_price_product_mp"]=>
      float(526.3)
    }
  }
  [4]=>
  array(1) {
    ["2020-05-03"]=>
    array(1) {
      ["best_price_product_mp"]=>
      float(526.3)
    }
  }
...
}
  
  

我希望結果是這樣的:

  array(100) {
  [1]=>
  array(2) {
    ["2020-04-18"]=>
    array(2) {
      ["best_price_product"]=>
      float(489.1)
      ["best_price_product_mp"]=>
      float(526.3)
    }
  }
  [2]=>
  array(1) {
    ["2020-04-19"]=>
    array(2) {
      ["best_price_product"]=>
      float(489.1)
      ["best_price_product_mp"]=>
      float(526.3)
    }
  }
  [3]=>
  array(2) {
    ["2020-04-20"]=>
    array(1) {
      ["best_price_product"]=>
      float(489.1)
      ["best_price_product_mp"]=>
      float(526.3)
    }
  }
  [4]=>
  array(1) {
    ["2020-04-21"]=>
    array(2) {
      ["best_price_product"]=>
      float(489.1)
      ["best_price_product_mp"]=>
      float(526.3)
    }
  }
[5]=> 
  array(1) {
    ["2020-05-03"]=>
    array(1) {
      ["best_price_product_mp"]=>
      float(526.3)
    }
  }
  ….
  }

在兩個arrays的合並中,除了合並的日期之外,還有其他在每個數組中唯一的日期。

謝謝

您可以展平 arrays 並將它們合並:

$result = array_merge_recursive(call_user_func_array('array_merge', $a1),
                                call_user_func_array('array_merge', $a2));

結果也將變平,類似於:

Array
(
    [2020-04-18] => Array
        (
            [best_price_product] => 1
            [best_price_product_mp] => 2
        ),
    [2020-04-19] => Array
        (
            [best_price_product] => 3
            [best_price_product_mp] => 4
        )
)

暫無
暫無

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

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