How to mount a JSON return?

Asked

Viewed 3,436 times

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?

  • It’s just that I don’t know how to do this, after manipulating the data. Just mount an array with the manipulated data?

  • That’s right you did

  • What do you mean? That’s what? I know that last code is right. But what about the top?

  • Take the result of the query and play json_enconde and print it with an echo.

  • 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>"; }

  • What you mean is that the bottom code works, and you want to do something similar to the top code? That’s it?

  • Exactly, @mgibsonbr.

  • you want to send the already formatted query and turn into json?

  • 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?

Show 5 more comments

2 answers

2


Format the date by the bank with date_format() so you don’t have to do it by php. Create a new array, format the currency value and 'stack' the items at the end of the function return the a string(json).

function mostraContasEntrada($id_empresa){    
    $pdo = conectar();
    $this->mostraDadosEntrada=$pdo->prepare(
        "SELECT c.categoria, sc.subcategoria, date_formart(data, '%d/%m/%Y'),  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();

    $lista = array();
    while ($r = $this->mostraDadosEntrada->fetch(PDO::FETCH_ASSOC)) {
        $r['valor'] = number_format($r['valor'],2,',','.');
        $r['subcategoria'] = utf8_encode($r['subcategoria']);
        $lista[] = $r;
    }

    return json_encode($lista);
}   

echo mostraContasEntrada($id);
  • "Parse error: syntax error, Unexpected ',' in /Applications/MAMP/htdocs/systems/systems_web/fluxo_de_box/fluxojoin_v_hap/classes/countEntrada.php on line 77" $Return[] = $data, $r['category'], utf8_encode($r['subcategory']), number_format($r['value'],2,',','.');

  • @Gustavosevero has a comma in the wrong place.

  • Where exactly? After formatting the value, assign it to a variable?

  • @Gustavosevero, leaves the code equal to the answer.

  • But I have more than one variable, not just number_format($r['value'],2,','.') Or you mean, show that doing this $r['value'] = number_format($r['value'],2,',','.'), I’m already assigning the formatted value at the proper position of the array, that’s it?

  • @Gustavosevero, already formats the value in $r and then assigned in $lista again

  • I got it, @rray.

  • Still, it gives the same error warning. My code looks like this: $dataP = explode("-", $r['data']); $data = $dataP[2]. '/'. $dataP[1]. '/'. $dataP[0]; $r['value'] = number_format($r['value'],2,',','. '); $Return[] = $data, $r['category'], utf8_encode($r['subcategory']), $r; '. utf8_encode($r['subcategory']). ' '.number_format($r['value'],2,','. ')." <br>"; echo json_encode($Return);

  • @Gustavosevero qual? puts the line in the comment

  • 1

    Next, it worked, the data are being returned, but in the following way: [{"category":"Sales","subcategory":"Miscellaneous Time-Frame","date":"04/11/2015","value":"100,00"}] As I am working with Angularjs, I don’t know if this will display the data correctly. I’ll try, but tomorrow

Show 6 more comments

1

The most direct way is to create an array of arrays, then convert to JSON in the same way as in the second code:

$return = array();
while ($r = $this->mostraDadosEntrada->fetch(PDO::FETCH_ASSOC)) {
    $dataP = explode("-", $r['data']);
    $data = $dataP[2].'/'.$dataP[1].'/'.$dataP[0];

    array_push($return, array($data, $r['categoria'], utf8_encode($r['subcategoria']), 
                       number_format($r['valor'],2,',','.')));
}
echo json_encode($return);

This will generate a JSON with the following structure:

[["01/02/2015", "cat1", "sub1", 1234], [...], ...]

If you prefer a JSON with objects, instead of arrays, like:

[{
    "data":"01/02/2015",
    "categoria":"cat1",
    "subcategoria":"sub1", 
    "valor":1234
 }, 
 {...}, 
 ...
]

Then just push an associative array on $return, instead of a common array:

    array_push($return, array(
        "data" => $data,
        "categoria" => $r['categoria'],
        "subcategoria" => utf8_encode($r['subcategoria']),
        "valor" => number_format($r['valor'],2,',','.')
    ));

You can adapt the keys of the above example as you think best.

  • Okay, I’ll try that.

  • Dude, this error appears: "<br /> <b>Fatal error</b>: Call to Undefined Function push() in <b>/Applications/MAMP/htdocs/systems/systems_web/fluxo_de_box/fluxojoin_v_hap/classes/containEntrate.php</b> on line <b><b><br />" E points to this line: $Return.push(array($data, $r['category'], utf8_encode($r['subcategory']), number_format($r['value'],2,',','.')));

  • @Gustavosevero It was bad, I do not have much experience with PHP, I confused the function array_push with the method push Javascript... Fix, now should work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.