Question

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?

Was it helpful?

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']);
        }
    }
}

OTHER TIPS

I now use some like this:

foreach ($a1 as $order => $result) {
    $a1[$order] = array_merge($a1[$order], current(Hash::extract($a2, '{n}.Post[id=' . $result['id'] . ']')));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top