简体   繁体   中英

Loading 2 arrays into one object PHP

I currently have code like this twice, one for each table

$sql = "SELECT * FROM Characters";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    
    $dataset = array();
    while($row = mysqli_fetch_assoc($result)) {
        $dataset[]=$row;
    }

} else {
    echo "0 results";
}

This works, and I get 2 separate arrays from 2 separate tables. I want to know how to put both of these PHP arrays into an object like you see in JSON. The nodes array from one table, and the links array from the other table.

{
 "nodes": [
    {"name": "Bob", "group": 1},
    {"name": "Bill", "group": 2}
 ],
 "links": [
    {"source": "Bill", "target": "Bob", "value": 1}
 ]
}

I've seen solutions that merge both arrays, but I need them to stay separated and I need both arrays to be in the same object . If there isn't a way to do this in PHP, is there a way I can send both PHP arrays to Javascript and then combined them in an object there? Thanks

Put the results of each query in separate arrays, for instance $nodes and $links . Then you can combine them with:

$results = ["nodes" => $nodes, "links" => $links];
echo json_encode($results);

As simply as

$result = [
    'nodes' => $array1,
    'links' => $array2,
];

$jsonResult = json_encode($result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM