1

I'm capturing the following data from MySQL:

table

Using PHP, I want to organize the data in two arrays: 'pagamentos' and 'recebimentos', sorted by 'mes' into a JSON object. Something like:

{ name: 'Recebimentos', data: [0.00, 11970.99, 2888.0]}, 
{ name: 'Pagamentos', data: [400.00, 6877.00, 500.00]}

I have:

$rows = $result->fetchAll(PDO::FETCH_ASSOC);

$recebimentos=array();
$pagamentos=array();

        foreach ($rows as $key) {
        if($key['fluxo']=='Recebimentos'){
            array_push($recebimentos, floatval($key['atual']));
        } elseif($key['fluxo']=='Pagamentos'){
            array_push($pagamentos, floatval($key['atual']));
        }
    };

        echo json_encode(array(
            'recebimentos' => array(name=> 'name', data=>$recebimentos),
            'pagamentos' => array(name=> 'name', data=>$pagamentos),
        ));

But this is returning:

{"recebimentos":{"name":"name","data":[0,11970.99,2888]},"pagamentos":{"name":"name","data":[400,6877,500]}}
2
  • It looks like the data is not making it into the recebimentos and pagamentos arrays. Are you sure that this $recebimentos[]=$key['real']; is what you want? Wouldn't it be $recebimentos[]=$key['atual'];? Commented Mar 31, 2014 at 16:53
  • Yes, exactly. I'll edit my question above, since it was a typo. Commented Mar 31, 2014 at 16:55

2 Answers 2

1

There are two spots that need changes - $key['real'] should be $key['atual'] or $key['actual']. Not sure if that's a copy-paste error, or if the column is actually named atual:

    foreach ($rows as $key) {
        if($key['fluxo']=='Recebimentos'){
            $recebimentos[]=$key['atual'];
        } elseif($key['fluxo']=='Pagamentos'){
            $pagamentos[]==$key['atual'];
        }
    };

And when you assign the name of the encoded data, you need the actual name, rather than 'name':

    echo json_encode(array(
        array(name=> 'recebimentos', data=>$recebimentos),
        array(name=> 'pagamentos', data=>$pagamentos)
    ));
Sign up to request clarification or add additional context in comments.

Comments

0

Replace

    foreach ($rows as $key) {
        if($key['fluxo']=='Recebimentos'){
            $recebimentos[]=$key['real'];
        } elseif($key['fluxo']=='Pagamentos'){
            $pagamentos[]==$key['real'];
        }
    };

by

    foreach ($rows as $key) {
        if($key['fluxo']=='Recebimentos'){
            $recebimentos[] = $key['actual']; // 'actual', not 'real'
        } elseif($key['fluxo']=='Pagamentos'){
            $pagamentos[] = $key['actual']; // just 1 '=' and 'actual', not 'real'
        }
    };

1 Comment

Sorry, I had a typo above, please see my edited question. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.