3
I have this code, below, where I manipulate some data. But after, I need to transform into a JSON object, as the example below.
<?php
function mostraContasEntrada($id_empresa){
$pdo = conectar();
$this->mostraDadosEntrada=$pdo->prepare(
"SELECT c.categoria, sc.subcategoria, data, valor
FROM entrada e
JOIN cat_entradas c
on c.id_categoria = e.categoria
JOIN sub_cat_entrada sc
on sc.id_subcategoria
WHERE id_empresa=:id_empresa
ORDER BY data DESC");
$this->mostraDadosEntrada->bindValue(":id_empresa", $id_empresa);
$this->mostraDadosEntrada->execute();
while ($r = $this->mostraDadosEntrada->fetch(PDO::FETCH_ASSOC)) {
$dataP = explode("-", $r['data']);
$data = $dataP[2].'/'.$dataP[1].'/'.$dataP[0];
echo $data.' '.$r['categoria'].' '.utf8_encode($r['subcategoria']).'
'.number_format($r['valor'],2,',','.')."<br>";
}
?>
I want to do this:
<?php
header('Content-Type: application/json');
$return = array();
while ($linha=$buscarUsuario->fetch(PDO::FETCH_ASSOC)) {
array_push($return, $linha);
}
echo json_encode($return);
?>
What doesn’t happen? What’s the problem?
– rray
It’s just that I don’t know how to do this, after manipulating the data. Just mount an array with the manipulated data?
– GustavoSevero
That’s right you did
– rray
What do you mean? That’s what? I know that last code is right. But what about the top?
– GustavoSevero
Take the result of the query and play json_enconde and print it with an echo.
– rray
The problem is this code: while ($r = $this->displayDadosEntrada->fetch(PDO::FETCH_ASSOC)) { $dataP = explode("-", $r['data']); $data = $dataP[2]. /'. $dataP[1]. '/'. $dataP[0]; echo $data. ' '.$r['category']. ' '.utf8_encode($r['subcategory']). ' '.number_format($r['value'],2,','.')." <br>"; }
– GustavoSevero
What you mean is that the bottom code works, and you want to do something similar to the top code? That’s it?
– mgibsonbr
Exactly, @mgibsonbr.
– GustavoSevero
you want to send the already formatted query and turn into json?
– rray
No.... I will speak differently. Let’s assume that this code below, which works, I had to manipulate data, to then make the return, as I should do?
– GustavoSevero