简体   繁体   English

PHP json_encode 2个数组

[英]PHP json_encode 2 arrays

I need to create a json with two (or more) arrays that can have other arrays inside. 我需要创建一个带有两个(或更多)数组的json,其中可以包含其他数组。 I did several tests, but I can never get a correct output. 我做了几次测试,但我永远无法得到正确的输出。 This is the output I would like to get to: 这是我想要的输出:

{
    "servizi" : [
        {"id": 1, "nomeservizio": "Menu","value": 1},
        {"id": 2, "nomeservizio": "Prenotazione","value": 0}
    ],

    "pietanze" : [

        {"tipopietanza": "PANINI","PANINI" : [
            {"id": 1, "nomepietanza": "Royal avec du fromage", "prezzo":      5.50, "ingredienti": "Hamburger di manzo, cetriolini sott'aceto, cheddar, cipolle, senape, ketchup"},
            {"id": 2, "nomepietanza": "Big Belly Burger", "prezzo": 5.50, "ingredienti": "Hamburger di manzo, cipolla,senape, salsa worchester, prezzemolo, aglio, peperone, lattuga"}
        ]},

        {"tipopietanza": "CONTORNI E STUZZICHINI", "CONTORNI E STUZZICHINI" :[
            {"id":1, "nomepietanza": "Caprese", "prezzo": 4.00, "ingredienti": "Mozzarella"},
            {"id":2, "nomepietanza": "Insalata", "prezzo": 3.50, "ingredienti": "Insalata"}
        ]}
    ]
}

I want to take the data from a database and this is the first part of the output where I get "servizi", now I want to get "pietanze" and put it like in the json I showed 我想从数据库中获取数据,这是输出的第一部分,我得到“servizi”,现在我想得到“pietanze”并把它放在我展示的json中

<?php

$user = 'root';
$pass = '';
$db = 'taurosdb';

$connect = mysqli_connect("localhost", "root", "", "taurosdb");  

  $sql = "-query that takes me the "servizi"-";  
           $result = mysqli_query($connect, $sql);  
           $json_array = array();  
           while($row = mysqli_fetch_assoc($result))  
           {  
                $json_array[] = $row;  
           }  
echo json_encode(array('servizi' => $json_array));

?>

Just make your array a variable so you can work with it. 只需将数组变为变量即可使用它。 Instead of this: 而不是这个:

echo json_encode(array('servizi' => $json_array));

You can say: 你可以说:

$my_big_array = ["servizi" => $json_array];

Then later on: 然后是:

$my_big_array["pietanze"] = $some_other_data;

Then at the end you can output the JSON. 然后在最后,您可以输出JSON。 Don't forget to set the Content-Type header. 不要忘记设置Content-Type标头。

header("Content-Type: application/json");
echo json_encode($my_big_array);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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