Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have json response like this

Array
(
    [0] => Array
        (
            [id] => 65070
            [date] => 2015-06-05
            [hour] => 0
            [total] => 18
        )

    [1] => Array
        (
            [id] => 65070
            [date] => 2015-06-05
            [hour] => 2
            [total] => 32
        )

    [2] => Array
        (
            [id] => 65070
            [date] => 2015-06-07
            [hour] => 0
            [total] => 27
        )

    [3] => Array
        (
            [id] => 65070
            [date] => 2015-06-07
            [hour] => 2
            [total] => 35
        )

    [4] => Array
        (
            [id] => 1838680
            [date] => 2015-06-05
            [hour] => 0
            [total] => 957
        )

    [5] => Array
        (
            [id] => 1838680
            [date] => 2015-06-05
            [hour] => 2
            [total] => 1266
        )

    [6] => Array
        (
            [id] => 1838680
            [date] => 2015-06-07
            [hour] => 0
            [total] => 409
        )

    [7] => Array
        (
            [id] => 1838680
            [date] => 2015-06-07
            [hour] => 2
            [total] => 1528
        )
)

I want output like this

id  Hour    2015-06-05  2015-06-07  Difference
65070   0   18  27  9
65070   2   32  35  3
1838680 0   957 409 -548
1838680 2   1266    

Hour is not fixed to 0 or 2. It can be more than 2 or 1 also

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
217 views
Welcome To Ask or Share your Answers For Others

1 Answer

I do not know what to write, it is routine code

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

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

echo "id hour ". $dates[0] . " " . $dates[1] . " " . "difference"."
";

foreach($newArray as $id => $hours)
  foreach($hours as $hour => $entry)
     echo  $id ." " . $hour  . " " 
           . $entry[$dates[0]] . " " 
           . $entry[$dates[1]] . " "
           . ($entry[$dates[1]] - $entry[$dates[0]]) . "
";

DEMO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...