-1

Please, help me to merge two multi dimensional arrays. It looks like:

Array
(
    [data] => Array
        (
            [1] => Array
                (
                    [id] => 1
                )

            [2] => Array
                (
                    [id] => 2
                )
        )
)

And second array

Array
(
    [0] => stdClass Object
        (
            [votes] => 45
        )

    [1] => stdClass Object
        (
            [votes] => 9
        )

)

Final output that i need:

Array
(
    [data] => Array
        (
            [1] => Array
                (
                    [id] => 1
                    [votes] => 1
                )

            [2] => Array
                (
                    [id] => 2
                    [votes] => 2
                )
        )
)

I have tried array_merge, array_merge_recursive, and some tests with foreach. But anything can't help me:( Pls, help!

marekful
  • 14,986
  • 6
  • 37
  • 59
azazaa
  • 39
  • 8

4 Answers4

0

If the keys are really shifted then this should work: (otherwise the -1 is not needed.)

<?php

foreach($array1['data'] as $key => &$subarray){
        $subarray['votes']=$array2[$key-1]->votes;
}
Lajos Veres
  • 13,595
  • 7
  • 43
  • 56
0

There's no built in function in PHP for that but you can loop through the first array and assign values from the second manually.

foreach($firstArray['data'] as $key => &$value) {
    $value['votes'] = $secondArray[$key]->votes;
}
marekful
  • 14,986
  • 6
  • 37
  • 59
0

Have you considered a foreach loop on the second array? My PHP is a quite rusty but here goes:

foreach($arrayOne["data"] as $key => $value) {
    $sub = $arrayTwo[$key];
    $value["votes"] = $sub["votes"];
}

Excuse any errors, written on a mobile in a hurry to catch the bus.

0

Use PHP function "array_merge_recursive" http://php.net/manual/en/function.array-merge-recursive.php and "array_values" to have indentic keys

$array_ret['data'] = array_merge_recursive(array_values($array1['data']), array_values($array2));
Yakub
  • 205
  • 2
  • 9