search

Home  >  Q&A  >  body text

javascript - array merging problem

These are the two arrays before merging

This is the merged array

How to write this foreach?

迷茫迷茫2710 days ago943

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-06-28 09:25:28

    Let me talk about my understanding of the purpose of the question first. These two arrays should be taken from two different tables. Date and a_id should be the same fields. Merging is also based on these two. If the date and a_id are the same, then To merge the data into an array, the following is the code:

    $array1 = array(..); // The first array merged
    $array2 = array(..); // The second array merged
    $array = array_merge($array1 , $array2); / / Combine two arrays
    $new_array = array();
    foreach($array as $v){

    foreach($v as $key => $val){
        if(array_key_exists($val['date'].'-'.$val['a_id'] , $new_array)){
            // 存在相同的数组下标说明两个数组有相同的date,a_id,那么直接合并
            $new_array[$val['date'].'-'.$val['a_id']] = array_merge($new_array[$val['date'].'-'.$val['a_id']],$val);
        }else{
            $new_array[$val['date'].'-'.$val['a_id']] = $val;
        }
    }

    }

    Explanation: The subscript of the processed array new_array is date-a_id, which is used as the only subscript

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-06-28 09:25:28

    I don’t know what to press

    reply
    0
  • Cancelreply