Thilina Sameera
Thilina Sameera

Reputation: 11

Need to create object

Array ( [0] => stdClass Object ( [download] => 8.63058 [date] => 2019 03 23 12:16 ) [1] => stdClass Object ( [download] => 10.94184 [date] => 2019 03 23 12:17 ) [2] => stdClass Object ( [download] => 11.37850 [date] => 2019 03 23 12:18 ) ) 


 Array ( [0] => stdClass Object ( [upload] => 2.95235 ) [1] => stdClass Object ( [upload] => 2.87732 ) [2] => stdClass Object ( [upload] => 3.58455 ) )

I need above mearge two arrays as below.

Array ( [0] => stdClass Object ( [download] => 8.63058 [upload]=>2.95235 [date] => 2019 03 23 12:16 ) [1] => stdClass Object ( [download] => 10.94184 [upload]=>2.87722 [date] => 2019 03 23 12:17 ) [2] => stdClass Object ( [download] => 11.37850 [upload]=>3.58455 [date] => 2019 03 23 12:18 ) )

Upvotes: 0

Views: 67

Answers (2)

Crustamet
Crustamet

Reputation: 104

TRY THIS 

$array1 = json_decode(json_encode($arr1), true); // convert to array
$array2 = json_decode(json_encode($arr2), true); // convert to array

$arr_merged = array_merge($array1, $array2); // merge both arrays 

$arr_merged = json_decode(json_encode($arr_merged)); // to make it back into an object

Upvotes: 0

Manuel Mannhardt
Manuel Mannhardt

Reputation: 2201

This will go over both arrays (they need to have the same keys!) and fetch all properties from the second array and write them into the object in array 1.

$arr1 = [ /* your objects */ ];
$arr2 = [ /* your objects */ ];

foreach ($arr1 as $index => $obj) {
    $vars = get_object_vars($arr2[$index]);

    foreach ($vars as $var => $value) {
        $obj->$var = $value;
    }
}

If it is just 'upload' you need from array 2, its even easier:

$arr1 = [ /* your objects */ ];
$arr2 = [ /* your objects */ ];

foreach ($arr1 as $index => $obj) {
    $obj->upload = $arr2[$index]->upload;
}

Upvotes: 1

Related Questions