merge 2 php arrays which aren't of the same length by value

Posted by Iain Urquhart on Stack Overflow See other posts from Stack Overflow or by Iain Urquhart
Published on 2010-04-04T11:38:28Z Indexed on 2010/04/04 11:43 UTC
Read the original article Hit count: 190

Filed under:
|
|

Excuse me if this has indeed been asked before, I couldn't see anything that fitted my needs out of the dozens of similar titled posts out there ;)

I'm trying to merge 2 php arrays which aren't of the same length, and merge them on a value that exists from identical key => values within both arrays.

My first query produces an array from a nested set:

array
(
    1 => array
    (
'node_id' => 1,
    'lft' => 1,
    'rgt' => 4,
    'moved' => 0,
    'label' => 'Home',
    'entry_id' => 1,
    'template_path' => '',
    'custom_url' => '/',
    'extra' => '',
    'childs' => 1,
    'level' => 0,
    'lower' => 0,
    'upper' => 0
    ),
    2 => array
    (
'node_id' => 2,
    'lft' => 2,
    'rgt' => 3,
    'moved' => 0,
    'label' => 'Home',
    'entry_id' => NULL,
    'template_path' => '',
    'custom_url' => 'http://google.com/',
    'extra' => '',
    'childs' => 0,
    'level' => 1,
    'lower' => 0,
    'upper' => 0
    )
);

My second array returns some additional key/values I'd like to insert to the above array:

array
(
'entry_id' => 1,
'entry_title' => 'This is my title',
);

I want to merge both of the arrays inserting the additional information into those that match on the key 'entry_id', as well as keeping the sub arrays which don't match.

So, by combining the two arrays, I'd end up with

array
(
    1 => array
    (
'node_id' => 1,
    'lft' => 1,
    'rgt' => 4,
    'moved' => 0,
    'label' => 'Home',
    'entry_id' => 1,
    'template_path' => '',
    'custom_url' => '/',
    'extra' => '',
    'childs' => 1,
    'level' => 0,
    'lower' => 0,
    'upper' => 0,
    'entry_title' => 'This is my title'
    ),
    2 => array
    (
'node_id' => 2,
    'lft' => 2,
    'rgt' => 3,
    'moved' => 0,
    'label' => 'Home',
    'entry_id' => NULL,
    'template_path' => '',
    'custom_url' => 'http://google.com/',
    'extra' => '',
    'childs' => 0,
    'level' => 1,
    'lower' => 0,
    'upper' => 0,
    'entry_title' => NULL
    )
);

Actually, writing this out makes me think I should do it via sql...

Any help/advice greatly appreciated...

© Stack Overflow or respective owner

Related posts about php

Related posts about arrays