user882670
user882670

Reputation:

PHP: Get two arrays from MySQL query table

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]}}

Upvotes: 1

Views: 79

Answers (2)

larsAnders
larsAnders

Reputation: 3813

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)
    ));

Upvotes: 1

doydoy44
doydoy44

Reputation: 5772

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'
        }
    };

Upvotes: 0

Related Questions