How do I combine two arrays in PHP based on a common key?

Posted by Eoghan O'Brien on Stack Overflow See other posts from Stack Overflow or by Eoghan O'Brien
Published on 2010-03-22T12:59:42Z Indexed on 2010/03/22 13:01 UTC
Read the original article Hit count: 328

Filed under:
|
|

Hi, I'm trying to join two associative arrays together based on an entry_id key. Both arrays come from individual database resources, the first stores entry titles, the second stores entry authors, the key=>value pairs are as follows:

array (
    'entry_id' => 1,
    'title' => 'Test Entry'
)   

array (
    'entry_id' => 1,
    'author_id' => 2

I'm trying to achieve an array structure like:

array (
    'entry_id' => 1,
    'author_id' => 2,
    'title' => 'Test Entry'
)

Currently, I've solved the problem by looping through each array and formatting the array the way I want, but I think this is a bit of a memory hog.

$entriesArray = array();
foreach ($entryNames as $names) {
    foreach ($entryAuthors as $authors) {
        if ($names['entry_id'] === $authors['entry_id']) {
            $entriesArray[] = array(
                'id' => $names['entry_id'],
                'title' => $names['title'],
                'author_id' => $authors['author_id']
            );                          
        }
    }
}

I'd like to know is there an easier, less memory intensive method of doing this?

© Stack Overflow or respective owner

Related posts about combine

Related posts about php