简体   繁体   中英

PHP - formatting array results

I wrote a query that calculate spending for each of last 7 days.

It returns results like..

 [
    {
        "Day": "Mon",
        "Total": "2"
    }
]

Now I need to format that json result so that Days go to 'labels' and total to 'data like:

    [
        'labels' => ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        'data' => [0, 0, 0, 0, 0, 0, 0]
    ];

I do not have any previous experience with formatting arrays, so this part looks confusing to me.

Here, this should do the trick

//This is your input data
$inputs = json_decode( "[{\"Day\":\"Mon\",\"Total\":2},{\"Day\":\"Tue\",\"Total\":4}]", TRUE);

//This is where to store the output
$output = array(
        "labels" => array(),
        "data"   => array(),
    );

//Loop all your inputs
foreach( $inputs as $daySpending){
    //Add the day as a label
    $output["labels"][] = $daySpending["Day"];

    //Add the amount as the data
    $output["data"][] = $daySpending["Total"];
}

echo "<pre>". print_r( $output, 1 ) ."</pre>";
$jsonArr = json_decode(' [{"Day": "Mon","Total": "2"},{"Day": "TUE", "Total": "3" }]', TRUE);

$temp =['labels' => [],'date' => []];
if(!empty($jsonArr)) {
  foreach($jsonArr as $arr) {
     array_push($temp['labels'], $arr['Day']);
     array_push($temp['date'], $arr['Total']); 
  }
}

Try this simple code

$resultData=array();
$jsondata='[{"Day": "Mon","Total": "2"}]';
$result=json_decode($jsondata,true);
foreach($result as $key => $value){
   $labels[]=$value['Day'];
   $data[]=$value['Total'];
}
$resultData['labels']=$labels;
$resultData['data']=$data;

echo json_encode($resultData);

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