Skip to content
Advertisement

Merge two 2d arrays and ensure that newly added rows use the next available id value

My code like this :

<?php 
    $a = array(
            array('id'=>1,'name'=>'chelsea'),
            array('id'=>2,'name'=>'mu')
    );
    $b = array(
            array('id'=>2,'name'=>'city'),
            array('id'=>3,'name'=>'liverpool')
    );
    $offset = end($a)['id'];
    $c = array_merge(
        $a, 
        array_map(
            function($v)use($offset){
                $v['id'] += $offset; 
                return $v;
            }, $b
        )
    );
?>

If the code run, the result like this :

Array (

[0] => Array ( [id] => 1 [name] => chelsea )

[1] => Array ( [id] => 2 [name] => mu )

[2] => Array ( [id] => 4 [name] => city )

[3] => Array ( [id] => 5 [name] => liverpool )

)

I want to change the result like this :

Array (

[0] => Array ( [id] => 1 [name] => chelsea )

[1] => Array ( [id] => 2 [name] => mu )

[2] => Array ( [id] => 3 [name] => city )

[3] => Array ( [id] => 4 [name] => liverpool )

)

How can I do it?

Note : The value on index id in array $b is dynamic. So the index id can have value between 1 – 5

Advertisement

Answer

Change $offset = end($a)['id']; to $offset = end($a)['id'] - $b[0]['id'] + 1; Live demo.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement