sql >> Database teknologi >  >> RDS >> Mysql

To forespørgsler mysql i ét objekt json

Jeg tror, ​​du kan prøve dette

$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'"); 

// I think, you'll get a single row, so no need to loop
$json = mysql_fetch_array($result, MYSQL_ASSOC);

$json2 = array();
while ($row = mysql_fetch_assoc($fetch)){
    $json2[] = array( 
        'name' => $row["name"],
        'age' => $row["age"],
        'city' => $row["city"]
    );
}
$json['people'] = $json2;
echo json_encode($json);
 

Resultat af print_r($json) burde være sådan noget her

Array ( [date] => 2013-07-20 [year] => 2013 [id] => 123456 [people] => Array ( [0] => Array ( [name] => First [age] => 60 [city] => 1 ) [1] => Array ( [name] => second [age] => 40 [city] => 2 ) ) )

Resultat af echo json_encode($json) burde være

{
    "date" : "2013-07-20",
    "year":"2013",
    "id":"123456",
    "people":
    [
        {
            "name" : "First",
            "age" : "60",
            "city" : "1"
        },
        {
            "name" : "second",
            "age" : "40",
            "city" : "2"
        }
    ]
}
 

Hvis du gør echo json_encode(array($json)) så får du hele din json pakket ind i et array, sådan noget her

[
    {
        "date" : "2013-07-20",
        "year":"2013",
        "id":"123456",
        "people":
        [
            {
                "name" : "First",
                "age" : "60",
                "city" : "1"
            },
            {
                "name" : "second",
                "age" : "40",
                "city" : "2"
            }
        ]
    }
]
 


  1. Bulk Indsæt SQL Server millioner af rekord

  2. Forebyggelse af SQL-injektion i Node.js

  3. LAST_INSERT_ID() MySQL

  4. Hvordan opdeles en varchar-kolonne som flere værdier i SQL?