簡體   English   中英

json數據轉換為php中正確的require數組格式

[英]json data into proper require array format in php

在php中,我正在獲取json數據,並在echo "<pre>"; 和這樣的print_r-(這是小數據,我得到的是大數據)

Array
(
    [0] => Array
        (
            [id] => 0
            [date] => 2015-05-30
            [total] => 8
        )

    [1] => Array
        (
            [id] => 0
            [date] => 2015-05-31
            [total] => 4
        )

    [2] => Array
        (
            [id] => 4863
            [date] => 2015-05-30
            [total] => 183
        )

    [3] => Array
        (
            [id] => 4863
            [date] => 2015-05-31
            [total] => 140
        )

    [4] => Array
        (
            [id] => 5126
            [date] => 2015-05-30
            [total] => 131292
        )
)

要求-我想以這種表格格式顯示Thid數據->

id  2015-05-30  2015-05-31  difference <br/> 
0       8           4           -4     <br/> 
4863    183        140          -43    <br/> 
5126    131292                         <br/>

由於此數據看起來像保存在數據庫中,因此我希望您可以確保數據始終來自兩個日期,並按這些日期排序(如示例數組中所示)。

如果是這樣,我可能會這樣:

$array = array(array('id' => 0, 'date' => '2015-05-30', 'total' => 8),
               array('id' => 0, 'date' => '2015-05-31', 'total' => 4),
               array('id' => 4863, 'date' => '2015-05-30', 'total' => 183),
               array('id' => 4863, 'date' => '2015-05-31', 'total' => 140),
               array('id' => 5126, 'date' => '2015-05-30', 'total' => 131292));

$newArray = array();
$dates = array();


foreach($array as $entry) {
  if(!isset($newArray[$entry['id']])) $newArray[$entry['id']] = array();
  if(!in_array($entry['date'], $dates)) array_push($dates, $entry['date']);
  array_push($newArray[$entry['id']], array($entry['total'], $entry['date']));
}

echo "id&nbsp;" . $dates[0] . "&nbsp;" . $dates[1] . "&nbsp;" . "difference&nbsp;<br/>";
foreach($newArray as $id => $entry) {
  echo $id . "&nbsp;" . (($entry[0][1]==$dates[0]) ? $entry[0][0] . "&nbsp;" . $entry[1][0] : "&nbsp;" . $entry[0][0]) .  "&nbsp;" . ((count($entry) == 2) ? $entry[1][0]-$entry[0][0] : "") ."&nbsp;<br>";
}

暫無
暫無

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

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