3
I have the following tables:
orcamento
storing information under the heading of the budget;orcamentoItens
that stores budget items;itens
that stores the details of the items.
(I’ll put the speakers in query that I use).
I can generate JSON in the following format for a single budget:
{
"id": "3",
"titular": "CARVALHO",
"data": "2019-04-02",
"status": "A",
"itens": [
{
"id": "2",
"nome": "PRODUCT SAMPLE 2",
"quantidade": "2",
"preco": "127.74"
},
{
"id": "4",
"nome": "PRODUCT SAMPLE 5",
"quantidade": "1",
"preco": "215.45"
}
]
}
To generate this JSON I use this code:
$id_orcamento = $_GET['id'];
$stmt = $con->query("SELECT id, titular, data, status FROM orcamentos WHERE status = 'A' and id = $id_orcamento LIMIT 1");
$orcamento=$stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $con->query("SELECT i.id, i.nome, oi.quantidade, oi.preco FROM orcamentoItens oi JOIN itens i ON i.id = oi.item WHERE oi.orcamento = $id_orcamento");
$itens = $stmt->fetchAll(PDO::FETCH_ASSOC);
$orcamento['itens']=$itens;
echo json_encode($orcamento);
How to generate the same JSON format for multiple budgets at once?
I know I can make one query list all the information from various budgets doing the JOIN of all the tables involved (I already have this query), however as it will repeat the information of the budget header, I do not know how to generate JSON in the format I need.
Puts all returns in an array, however you need it, then json_enconde everything
– Otto
Okay, but how do you put all budget items within the key items in the array? I need JSON to maintain the format I put in the question, if you do the
json_encode
of the query with theJOIN's
will generate multiple records with repeated header.– Laércio Lopes
So let’s go.... the bank you know is Voce, it is much easier to assemble it within an array as your need .... Once ready you convert this array to json. Here you will find a path to solving your problem. Not his solution, hardly anyone will do for you.
– Otto
Really? Why did I ask that question right here? Oh man, thank you so much!
– Laércio Lopes