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

后端 未结 4 623
一生所求
一生所求 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条回答
  •  猫巷女王i
    2021-01-23 04:58

    If both arrays are in the same order, the code is pretty straightforward:

    $a = array(
        array('5/2/2013', '9:31:00 AM', '0.395', '0.395', '302.855', '0.563'),
        array('5/2/2013', '9:33:00 AM', '0.383', '0.383', '303.431', '0.563'),
    );
    
    $b = array(
        array('5/2/2013', '9:31:00 AM', '-1.000', '-1.000', '-1.000', '-1.670', '-1.000', '-11.000'),
        array('5/2/2013', '9:33:00 AM', '-1.000', '-1.000', '-1.000', '-1.670', '-1.000', '-11.000'),
    );
    
    
    $i = new MultipleIterator(MultipleIterator::MIT_NEED_ALL | MultipleIterator::MIT_KEYS_ASSOC);
    $i->attachIterator(new ArrayIterator($a), 'a');
    $i->attachIterator(new ArrayIterator($b), 'b');
    
    $result = [];
    foreach ($i as $v) {
        $result[] = array_merge($v['a'], array_slice($v['b'], 2));
    }
    print_r($result);
    

    You basically iterate over both arrays at the same time and for each element construct the final array by merging the first with the second (skipping the common part).

    Result:

    Array
    (
        [0] => Array
            (
                [0] => 5/2/2013
                [1] => 9:31:00 AM
                [2] => 0.395
                [3] => 0.395
                [4] => 302.855
                [5] => 0.563
                [6] => -1.000
                [7] => -1.000
                [8] => -1.000
                [9] => -1.670
                [10] => -1.000
                [11] => -11.000
            )
    
        [1] => Array
            (
                [0] => 5/2/2013
                [1] => 9:33:00 AM
                [2] => 0.383
                [3] => 0.383
                [4] => 303.431
                [5] => 0.563
                [6] => -1.000
                [7] => -1.000
                [8] => -1.000
                [9] => -1.670
                [10] => -1.000
                [11] => -11.000
            )
    )
    

提交回复
热议问题