【发布时间】:2017-02-01 13:16:38
【问题描述】:
我正在尝试使用源自 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){
.
.
}
我已经尝试使用这个 sn-p(和许多其他)按日期([“start”])对单个项目进行排序 - 日历会议的开始,但到目前为止没有运气。我也研究过合并对象,但没有运气。我是 PHP 的新手,但对编程的基础知识相当了解,所以我希望有人能指出我正确的方向 - 我会很感激:
usort($results, function($a, $b) {
return $a['items']['start'] - $b['items']['start'];
});
var_dump( $results );
【问题讨论】:
-
请尝试使用
strtotime($a['items']['start']) - strtotime($b['items']['start'])或更好地创建DateTime object,然后在usort中子您的值 -
因为我不需要 ["response-testx"] 级别 - 有没有办法合并或展平数组 - 将所有记录向上移动一步,并摆脱 ['response -testx'] 级别?
-
@petrusjak 如果你想减小数组大小,我更新了答案。
标签: php arrays sorting google-calendar-api google-api-php-client