Use the array_merge
, the array_push
treats array
as a stack, and adds past variables as arguments at the end of it, so you end up with this structure:
array(3) {
["fruta1"]=>
string(7) "laranja"
["fruta2"]=>
string(7) "morango"
[0]=>
array(2) {
["fruta3"]=>
string(6) "goiaba"
["fruta4"]=>
string(3) "uva"
}
}
The array_merge
will combine/merge array widgets:
<?php
$itens1= array("fruta1"=>"laranja", "fruta2"=>"morango");
$itens2= array("fruta3"=>"goiaba", "fruta4"=>"uva");
echo json_encode(array_merge($itens1, $itens2));
?>
Another more manual way to solve your problem by keeping the associative keys would be with a read and assignment loop:
<?php
$itens1= array("fruta1"=>"laranja", "fruta2"=>"morango");
$itens2= array("fruta3"=>"goiaba", "fruta4"=>"uva");
foreach($itens2 as $key=>$item){
$itens1[$key] = $item;
}
echo json_encode($itens1);
?>
This second way you could use the array_push
, but would lose the associative key:
<?php
$itens1= array("fruta1"=>"laranja", "fruta2"=>"morango");
$itens2= array("fruta3"=>"goiaba", "fruta4"=>"uva");
foreach($itens2 as $item){
array_push($itens1, $item);
}
echo json_encode($itens1);
/* Resultado array
array(4) {
["fruta1"]=>
string(7) "laranja"
["fruta2"]=>
string(7) "morango"
[0]=>
string(6) "goiaba"
[1]=>
string(3) "uva"
}
Resultado json
{"fruta1":"laranja","fruta2":"morango","0":"goiaba","1":"uva"}
*/
?>
Possible duplicate of What is the difference between the union of an array via soma operator and the array_merge function?
– Woss