簡體   English   中英

PHP - 格式化數組結果

[英]PHP - formatting array results

我寫了一個查詢來計算過去 7 天的每一天的支出。

它返回結果如..

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

現在我需要格式化該 json 結果,以便 Days 轉到“標簽”並總計到“數據,例如:

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

我以前沒有任何格式化數組的經驗,所以這部分對我來說看起來很混亂。

在這里,這應該可以解決問題

//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']); 
  }
}

試試這個簡單的代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM