Home  >  Q&A  >  body text

php - Ask for advice: How to merge two-dimensional arrays when the two fields store_id and source are the same?

array(5) {
  [0]=>
  array(14) {
    ["id"]=>
    string(3) "143"
    ["store_id"]=>
    string(3) "504"
    ["goodsid"]=>
    string(2) "15"
    ["source"]=>
    string(1) "2"
  }
  [1]=>
  array(14) {
    ["id"]=>
    string(3) "142"
    ["store_id"]=>
    string(3) "503"
    ["goodsid"]=>
    string(2) "33"
    ["source"]=>
    string(1) "2"
  }
  [2]=>
  array(14) {
    ["id"]=>
    string(3) "141"
    ["store_id"]=>
    string(3) "638"
    ["goodsid"]=>
    string(2) "41"
    ["source"]=>
    string(1) "1"
  }
  [3]=>
  array(14) {
    ["id"]=>
    string(3) "140"
    ["store_id"]=>
    string(3) "638"
    ["goodsid"]=>
    string(2) "41"
    ["source"]=>
    string(1) "1"
  }
}

How to merge such arrays by making the two fields store_id and source the same?

过去多啦不再A梦过去多啦不再A梦2660 days ago685

reply all(3)I'll reply

  • 三叔

    三叔2017-06-10 09:49:30

    No ready-made functions. I can only write it myself, and I don’t understand what you mean by merging. . .
    You can cycle through the data.
    New data uses the two fields $store_id.'_'.$source as key
    $data[$store_id.'_'.$source][] = $_data;
    This way, or how you want to handle it

    reply
    0
  • 漂亮男人

    漂亮男人2017-06-10 09:49:30

    I don’t want to write code, just my thoughts
    1. Since the merger, if id and goodsid cannot be overwritten, we can only use a three-layer structure array, that is, store_id and source are the parent class as one layer, and id and goodsid subclasses are one layer.
    2. Merge the two fields with the same store_id and source, that is, merge the two fields into a new array as the key value. If there are new elements, re-add all the information. If not, add the child elements directly

    reply
    0
  • ringa_lee

    ringa_lee2017-06-10 09:49:30

    The mapping method using hashmap:
    1. Construct a data structure in the form of hashmap, use the store_id and source combination as a key, use a variable array as the value, and store the entire data corresponding to the store_id and source into the variable array.
    2. To facilitate the two-dimensional array, if the key combined by store_id and source already exists in the constructed data structure, then put the entire data corresponding to store_id and source into the variable array corresponding to the key. If it does not exist, add one The new key-value pair also uses the combined value of source and store_id as the key, and the variable array as the value. Put the entire data corresponding to source and store_id into the variable array corresponding to key.
    3. Convenient hashmap to merge the data in the array corresponding to each key.

    reply
    0
  • Cancelreply