简体   繁体   中英

PHP: Get two arrays from MySQL query table

I'm capturing the following data from MySQL:

表

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM