Join two arrays in one with PHP

Asked

Viewed 585 times

3

I have the following PHP:

<?php
$itens1= array("fruta1"=>"laranja", "fruta2"=>"morango");
$itens2= array("fruta3"=>"goiaba", "fruta4"=>"uva");
array_push($itens1, $itens2);
echo json_encode($itens1);
?>

I’d like him to return:

{"fruta1":"laranja","fruta2":"morango","fruta3":"goiaba","fruta4":"uva"}

But it’s not working, when I run PHP it returns:

{"fruta1":"laranja","fruta2":"morango","0":{"fruta3":"goiaba","fruta4":"uva"}}

I mean, there’s a "0" there and two more keys. I’ve researched and tried several ways but I’m not getting the desired result.

From now on I thank anyone who can help me.

1 answer

7


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"}
    */ 
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.