php - how to merge 2d array that have different no of element for each array

后端 未结 4 652
一生所求
一生所求 2021-01-23 04:24

I have 2 set of 2d array and i want merge into 1 2d array. but the number of element in each array its not same and for the first 2 element is same and i don\'t want to duplicat

4条回答
  •  再見小時候
    2021-01-23 04:53

    It depends a lot on what your actual goal is. For instance, from your example, it seems that you want to use the date [index 0] (and possibly the time [index 1]) as a "primary key" of sorts, to control how data is merged.

    There is no suitable function for this built in to PHP (as you've noticed, array_merge_recursive doesn't do what you want): you'll have to roll your own. There are a lot of "edge cases" to consider.

     $a1_item ){
                if( 
                    ! empty( $a1_item[0] )
                    && ! empty( $a1_item[1] )
                    && $a1_item[0] === $a2_item[0] 
                    && $a1_item[1] === $a2_item[1] 
                ){
                    // merge the two arrays
                    // filter duplicate values
                    // assign resulting array to the original index in $a1
                    $a1[$a1_key] = array_unique( 
                        array_merge_recursive( $a1_item,$a2_item )
                    );
                    // set this item as "false" so it won't be appended to $a1
                    $a2_item = false;
                    // stop; continue with next item in $a2
                    break;
                }
            }
            // if $a2_item was merged, it is now false;
            // otherwise, append it to the $a1 array
            if( $a2_item ){
                $a1[] = $a2_item;
            }
        }
        // return the $a1 array
        return $a1;
    }
    

    tested.

    $a1 = [
        0 => [
            0 => '25/2/2013'
           ,1 => '8.45 a.m'
           ,2 => '9.98'
        ]
       ,1 => [
            0 => '25/2/2013'
           ,1 => '8.46 a.m'
           ,2 => '9.02'
        ]
    ];
    $a2 = [   
        0 => [
            0 => '25/2/2013'
           ,1 => '8.45 a.m'
           ,2 => '1.23'
           ,3 => '6.1'
        ]
       ,1 => [
            0 => '25/2/2013'
           ,1 => '8.46 a.m'
           ,2 => '1.75'
           ,3 => '3.5'
        ]
    ];
    
    var_dump( key_01_merge( $a1,$a2 ) );
    

    outputs:

    /*
    array(2) {
      [0]=>
      array(5) {
        [0]=>
        string(9) "25/2/2013"
        [1]=>
        string(8) "8.45 a.m"
        [2]=>
        string(4) "9.98"
        [5]=>
        string(4) "1.23"
        [6]=>
        string(3) "6.1"
      }
      [1]=>
      array(5) {
        [0]=>
        string(9) "25/2/2013"
        [1]=>
        string(8) "8.46 a.m"
        [2]=>
        string(4) "9.02"
        [5]=>
        string(4) "1.75"
        [6]=>
        string(3) "3.5"
      }
    }
    */
    

提交回复
热议问题