Two queries mysql in one object json

前端 未结 3 862
孤街浪徒
孤街浪徒 2021-01-03 17:11

I have two tables that I want to convert them to json like this:

[
   {
      \"date\":\"2013-07-20\",
      \"id\":\"123456\",
      \"year\":\"2013\",
             


        
3条回答
  •  不知归路
    2021-01-03 17:39

    I think you may try this

    $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);
    

    Result of print_r($json) should be something like this

    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
                    )
    
            )
    
    )
    

    Result of echo json_encode($json) should be

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

    If you do echo json_encode(array($json)) then you will get your whole json wrapped in an array, something like this

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

提交回复
热议问题