json数据在php中正确需要数组格式

时间:2015-06-06 06:56:23

标签: php arrays json

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

要求 - 我想以这种表格格式显示这些数据 - &gt;

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

1 个答案:

答案 0 :(得分:0)

由于此数据看起来像保存在数据库中,我希望您可以确保数据始终来自两个日期,按这些日期排序(如示例数组中所示)。

如果是这种情况,我可能会这样做:

$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>";
}