我正在尝试使用源自 Google Calendar Batch 请求的对象对这个数组进行排序,并使用此结果数组对对象进行排序:
array(3) {
["response-test0"]=>;
object(Google_Service_Calendar_Events)#46 (17) {
.
.
.
["items"]=>;
array(1) {
[0]=>;
array(20) {
.
.
["start"]=>;
array(1) {
["dateTime"]=>;
string(25) "2017-02-01T10:00:00+01:00"
}
.
.
.
["response-test1"]=>;
object(Google_Service_Calendar_Events)#46 (17) {
.
.
.
["items"]=>;
array(1) {
[0]=>;
array(20) {
.
.
["start"]=>;
array(1) {
["dateTime"]=>;
string(25) "2017-02-01T11:00:00+01:00"
}
.
.
.
["response-test3"]=>;
object(Google_Service_Calendar_Events)#46 (17) {
.
.
.
["items"]=>;
array(1) {
[0]=>;
array(20) {
.
.
["start"]=>;
array(1) {
["dateTime"]=>;
string(25) "2017-02-01T11:00:00+01:00"
}
.
.
这是获取数据的代码:
$arrlength = count($calendarId);
for ($x = 0; $x <= $arrlength-1; $x++) {
$results = $service->events->listEvents($calendarId[$x], $optParams);
$batch->add($results, "test" .$x);
};
$results = $batch->execute();
生成的数组包含名为 ["response-test0"]、["response-test1"] 和 ["response-test2"] 的对象(在本例中),如我的数组中所示示例。
编辑:据我所知,数组对象与关联数组混淆的事实似乎在答案中缺失(或者我错了)?在对象内部搜索的建议似乎在方向正确,但我无法完全测试这一点,因为没有考虑“顶层”['response_x']。
对开始日期进行排序的结构(不是单独对每个对象中的日期进行排序):
array(3) {
["response-test0"]
Object(Google_Service_Calendar_Events)#46(17){
.
.
}
["response-test1"]
Object(Google_Service_Calendar_Events)#46(17){
.
.
}
["response-test2"]
Object(Google_Service_Calendar_Events)#46(17){
.
.
}
我尝试使用此代码片段(以及许多其他代码片段)按日期([“开始”])对各个项目进行排序 - 日历 session 的开始,但到目前为止没有运气。我也考虑过合并对象,但没有成功。我是 PHP 新手,但对编程基础知识相当了解,所以我希望有人能给我指出正确的方向 - 我将不胜感激:
usort($results, function($a, $b) {
return $a['items']['start'] - $b['items']['start'];
});
var_dump( $results );
最佳答案
您可以使用 DateTime 对象来比较日期:
function cmpDate($a, $b) {
// To confirm expected result, dump the data for inspection.
//var_dump($a);
//var_dump($b);
// Option 1:
//$date1 = new \DateTime($a['items'][0]['start']['dateTime'])->getTimestamp();
//$date2 = new \DateTime($b['items'][0]['start']['dateTime'])->getTimestamp();
// Option 2
$date1 = new \DateTime($a->items[0]['start']['dateTime'])->getTimestamp();
$date2 = new \DateTime($b->items[0]['start']['dateTime'])->getTimestamp();
// usort compares integers and orders it accordingly.
return $date1 - $date2;
}
usort($results, 'cmpDate');
我使用时间戳,这样您就不需要将日期格式化为字符串。
来源:
http://php.net/manual/en/class.datetime.php
http://php.net/manual/en/function.usort.php
为了回应您关于通过删除第一层重新排列数组的评论,您可以尝试以下操作。请注意,键对于了解哪个记录很重要。
$newArr = [];
foreach ($results as $key => $data) {
// echo $key; // response-test0
// You can reduce the array as much as you like.
// $newArr[] = $data;
// $newArr[] = $data->items['start'];
$newArr[] = $data->items['start']['dateTime'];
// In case you want to preserve the key
// $newArr[$key] = $data->items['start']['dateTime'];
}
关于php - 按对象中的日期对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41980797/