PHP-格式化数组结果

时间:2018-11-22 11:03:42

标签: php arrays json

我编写了一个查询,用于计算最近7天中的每一天的支出。

它返回类似的结果。

while ((line = br.nextLine()) != null)

现在我需要格式化json结果,以便将Days转到“ labels”并总计为“ data like”:

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

我以前对格式化数组没有任何经验,所以这部分令我感到困惑。

3 个答案:

答案 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>";

答案 1 :(得分:0)

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

答案 2 :(得分:0)

尝试这个简单的代码

    public  object NextEnumItem(object currentEnumItem) 
    {
        if (!currentEnumItem.GetType().IsEnum) throw new 
                ArgumentException(String.Format("Argument is not an Enum"));
        Array Arr = Enum.GetValues(currentEnumItem.GetType());
        int j = Array.IndexOf(Arr,currentEnumItem) + 1;
        return (Arr.Length == j) ? currentEnumItem : Arr.GetValue(j);
    }

    public object PreviousEnumItem(object currentEnumItem)
    {
        if (!currentEnumItem.GetType().IsEnum)
            throw new ArgumentException(String.Format("Argument is not an Enum"));
        Array Arr = Enum.GetValues(currentEnumItem.GetType());
        int j = Array.IndexOf(Arr, currentEnumItem) - 1;
        return (j==-1) ? currentEnumItem : Arr.GetValue(j);
    }