Skip to content

Instantly share code, notes, and snippets.

@Waicung
Last active May 17, 2017 12:28
Show Gist options
  • Save Waicung/aed94158c3893e163ab83d1e0127991a to your computer and use it in GitHub Desktop.
Save Waicung/aed94158c3893e163ab83d1e0127991a to your computer and use it in GitHub Desktop.
medium between Identifying Wechat Data API response and storage
<?php
/*
composer requires:
"require": {
"nesbot/carbon": "^1.22"
}
*/
require __DIR__ . '/vendor/autoload.php';
/*sample response in array*/
$response = [
[
"ref_date"=> "2014-12-07",
"user_source"=> 0,
"new_user"=> 0,
"cancel_user"=> 0
],
[
"ref_date"=> "2014-12-07",
"user_source"=> 1,
"new_user"=> 1,
"cancel_user"=> 1
],
[
"ref_date"=> "2014-12-07",
"user_source"=> 2,
"new_user"=> 2,
"cancel_user"=> 2
],
[
"ref_date"=> "2014-12-08",
"user_source"=> 0,
"new_user"=> 0,
"cancel_user"=> 0
],
[
"ref_date"=> "2014-12-10",
"user_source"=> 0,
"new_user"=> 0,
"cancel_user"=> 0
],
];
/*day range*/
$from='2014-12-06';
$to='2014-12-12';
$start = new Carbon\Carbon($from);
$end = new Carbon\Carbon($to);
/*index for loop through the response array*/
$index = 0;
/*reverse the response for array pop*/
$reverse = array_reverse($response);
$current = $start->copy();
/*simulate a database*/
$results = [];
/*loop through all the response requested*/
while($current->between($start,$end)){
$data = array_pop($reverse);
/*check if any response data left*/
if ($data) {
/*when the first date of the response does not match the current date*/
while ($data['ref_date']!==$current->toDateString()) {
/*check if the entry for current date already exist*/
if(!in_array($current->toDateString(), $results)){
/*insert the data if not exist*/
array_push($results, $current->toDateString());
echo 'while loop no data for '. $current->toDateString();
echo '<br>';
}
/*add one day to the current date*/
$current->addDay();
}
/*store the match data*/
array_push($results, $current->toDateString());
echo 'store data for '. $data['ref_date'];
echo 'cancel_user:'. $data['cancel_user'];
echo '<br>';
}
else{
/*check if the entry of the data already exist*/
if(!in_array($current->toDateString(), $results)){
array_push($results, $current->toDateString());
echo 'null no data for '. $current->toDateString();
}
$current->addDay();
}
echo '<br>';
}
/* output
while loop no data for 2014-12-06
store data for 2014-12-07cancel_user:0
store data for 2014-12-07cancel_user:1
store data for 2014-12-07cancel_user:2
store data for 2014-12-08cancel_user:0
while loop no data for 2014-12-09
store data for 2014-12-10cancel_user:0
null no data for 2014-12-11
null no data for 2014-12-12
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment