Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

json data into proper require multiple array format in php

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...