aniruddh aniruddh - 7 months ago 13
PHP Question

How to add one array value to existing array?

I'm trying to add one array values with existing array values ,but i'm stuck how to add them

Array-1

[main] => Array
(
[0] => stdClass Object
(
[clientID] => 2
[maintenance_due] => 2016-05-09 00:00:00
[complete_maintenance] => 1
[description] => dfdff
[created_at] => 2016-05-01 00:00:00
[completed_on] => 2016-05-06 00:00:00
[name] => Bottel packing
[type_id] => 1
[machinecode] => HITBTP001
[model_no] => ModelA
[created_date] => 2016-03-27 06:55:05
[updated_date] => 0000-00-00 00:00:00
)

)


Array-2

[dt] => Array
(
[dtm] => 0
[edm] => 1
)


I want like this

[main] => Array
(
[0] => stdClass Object
(
[clientID] => 2
[maintenance_due] => 2016-05-09 00:00:00
[complete_maintenance] => 1
[description] => dfdff
[created_at] => 2016-05-01 00:00:00
[completed_on] => 2016-05-06 00:00:00
[name] => Bottel packing
[type_id] => 1
[machinecode] => HITBTP001
[model_no] => ModelA
[created_date] => 2016-03-27 06:55:05
[updated_date] => 0000-00-00 00:00:00
[dtm] => 0
[edm] => 1


)

)


I'm trying
array_push
function and also use foreach but isn't working .

Please suggest how can i do this.

Answer

The solution using array_merge function and conversion(casting) from array into object and vice versa(only for basic stdClass objects):

// $array1 is your first array with 'main' key
// $array2 is your second array with 'dt' key

$main_arr = (array) current($array1['main']);  // converting object into array
$merged = array_merge($main_arr, $array2['dt']);  // combining "properties"

$array1['main'] = [(object) $merged]; // saving object with additional properties back to the initial array

print_r($array1); // will give the expected output