Search code examples
phpjsonarray-merge

trying to combine these two json arrays in php


I've tried things like json_combine and array_merge but I can't figure out how to do this.

  $query2 = "SELECT DISTINCT cat_id,cat_name FROM review WHERE user_id = ? AND public_or_private = 0";
    $stmt2 = $con->prepare($query2) or die(mysqli_error($con));
    $stmt2->bind_param('i', $user_id) or die ("MySQLi-stmt binding failed ".$stmt2->error);
    $stmt2->execute() or die ("MySQLi-stmt execute failed ".$stmt2->error);
    $result2 = $stmt2->get_result();

                    $array1 = array();

                    while ($row = mysqli_fetch_assoc($result2)) {

                        $array1['results'][] = $row;

                    }

echo json_encode($array1);

The json_encode gives me:

{"results":[{"cat_id":4,"cat_name":"dentist"}]}

And further down in my code I have:

$query3 = "SELECT DISTINCT cat_id,cat_name FROM review WHERE public_or_private = 2";
                $result3 = mysqli_query($con,$query3);

                $array2 = array();

                while($row = mysqli_fetch_assoc($result3)) {

                $array2['results'][] = $row;

                }  

echo json_encode($array2);

The json_encode gives me:

{
    "results": [{
        "cat_id": "8",
        "cat_name": "dental hygienist"
    }, {
        "cat_id": "5",
        "cat_name": "stocktaker"
    }, {
        "cat_id": "9",
        "cat_name": "builder"
    }]
}

So in total I have two json arrays:

{
    "results": [{
        "cat_id": 4,
        "cat_name": "dentist"
    }]
} 

{
    "results": [{
            "cat_id": "8",
            "cat_name": "dental hygienist"
        }, {
            "cat_id": "5",
            "cat_name": "stocktaker"
        },
        {
            "cat_id": "9",
            "cat_name": "builder"
        }
    ]
}

But how can I combine these into one like:

{
        "results": [{
                "cat_id": 4,
                "cat_name": "dentist"
            }, {
                "cat_id": "8",
                "cat_name": "dental hygienist"
            }, {
                "cat_id": "5",
                "cat_name": "stocktaker"
            },
            {
                "cat_id": "9",
                "cat_name": "builder"
            }
        ]
    }

I tried things like:

 $jsonArray = array();
foreach (array_combine( $array1, $array2 ) as $name => $value) {
    $jsonArray[] = array('cat_id' => $name, 'cat_name' => $value);
}

echo $json = json_encode($jsonArray); 

but still couldn't get it to work properly.


Solution

  • I guess you want to use array_merge_recursive instead.

    echo json_encode(array_merge_recursive($array1, $array2));