phpsortingcakephpmergearray-merge

CakePHP Fastest and better merge arrays


I has two arrays (the same models), like bellow:

Array (
    [0] => Array (
        [id] => 17
        [user_id] => 1
    )
    [1] => Array (
        [id] => 8
        [user_id] => 1
    )
    [2] => Array  (
        [id] => 9
        [user_id] => 1
    )
)

and

Array (
    [0] => Array (
        [Post] => Array (
            [id] => 9
            [name] => name1
            [slug] => slug1
        )
    )
    [1] => Array (
        [Post] => Array (
            [id] => 17
            [name] => other name
            [slug] => other_slug
        )
    )
    [2] => Array (
        [Post] => Array (
            [id] => 8
            [name] => lorem
            [slug] => lorem_slug
        )
    )
)

How to merge these two array by field id in format like first array?


Solution

  • I am still looking for a more elegant solution, but this one seems to work.

    $a1 = [
        ['id' => 17, 'user_id' => 1],
        ['id' => 8, 'user_id' => 2],
        ['id' => 9, 'user_id' => 3],
    ];
    
    $a2 = [
        ['Post' => ['id' => 9, 'name' => 'name1', 'slug' => 'slug1']],
        ['Post' => ['id' => 17, 'name' => 'other name', 'slug' => 'other_slug']],
        ['Post' => ['id' => 8, 'name' => 'lorem', 'slug' => 'lorem_slug']],
    ];
    $a2 = Hash::extract($a2, '{n}.Post');
    
    foreach ($a1 as $key => $value) {
        $a1['id_' . $value['id']] = $value;
        unset($a1[$key]);
    }
    
    foreach ($a2 as $key => $value) {
        $a2['id_' . $value['id']] = $value;
        unset($a2[$key]);
    }
    
    $a3 = array_values(array_replace_recursive($a1, $a2));
    debug($a3);
    

    Second, easier way:

    foreach ($a1 as &$item) {
        foreach ($a2 as $item2) {
            if ($item2['Post']['id'] == $item['id']) {
                $item = array_merge($item, $item2['Post']);
            }
        }
    }