首页 > 解决方案 > 按日期计数对数组进行分组

问题描述

我一直在使用一些测试数据和来自 MariaDB 表的以下查询来获取 Google 图表中图表的值:

google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([

['Date', 'Calls'],
<?php 
$query = "SELECT count(origin) AS count, start FROM outbound GROUP BY LEFT(start, 10) ORDER BY start";
        $exec = mysqli_query($con,$query);
        while($row = mysqli_fetch_array($exec)){


        // Format Start Date
        $start = date('Y/d/m', strtotime($row['start'])); 
        echo "['".$start."',".$row['count']."],";
        }

现在我正在尝试更改它以通过 API 调用从远程服务获取实时数据,而不是给我一个名为的数组中的值$calls

下面的代码按预期创建日期,但我无法解决如何按日期对调用进行分组,就像我之前在选择查询中所做的那样,以获得正确的计数:

foreach ($calls as $call) {
        // Format Start date as Y-m-D to group by date instead of exact timestamp
        $start = date_format($call->startTime, 'Y-m-d');
        
        $count = count($calls);
        echo "['".$start."',".$count."],";
    }
    

谁能指出我正确的方向?TIA

下面的示例响应:

Array
(
    [0] => Twilio\Rest\Api\V2010\Account\CallInstance Object
        (
            [_recordings:protected] => 
            [_notifications:protected] => 
            [_feedback:protected] => 
            [_payments:protected] => 
            [version:protected] => Twilio\Rest\Api\V2010 Object
                (
                    [_accounts:protected] => 
                    [_account:protected] => Twilio\Rest\Api\V2010\AccountContext Object
                        (
                            [_addresses:protected] => 
                            [_applications:protected] => 
                            [_authorizedConnectApps:protected] => 
                            [_availablePhoneNumbers:protected] => 
                            [_balance:protected] => 
                            [_calls:protected] => Twilio\Rest\Api\V2010\Account\CallList Object
                                (
                                    [_feedbackSummaries:protected] => 
                                    [version:protected] => Twilio\Rest\Api\V2010 Object
 *RECURSION*
                                    [solution:protected] => Array
                                        (
                                            [accountSid] => ***************************
                                        )

                                    [uri:protected] => /Accounts/***************************/Calls.json
                                )

                            [_conferences:protected] => 
                            [_connectApps:protected] => 
                            [_incomingPhoneNumbers:protected] => 
                            [_keys:protected] => 
                            [_messages:protected] => 
                            [_newKeys:protected] => 
                            [_newSigningKeys:protected] => 
                            [_notifications:protected] => 
                            [_outgoingCallerIds:protected] => 
                            [_queues:protected] => 
                            [_recordings:protected] => 
                            [_signingKeys:protected] => 
                            [_sip:protected] => 
                            [_shortCodes:protected] => 
                            [_tokens:protected] => 
                            [_transcriptions:protected] => 
                            [_usage:protected] => 
                            [_validationRequests:protected] => 
                            [version:protected] => Twilio\Rest\Api\V2010 Object
 *RECURSION*
                            [solution:protected] => Array
                                (
                                    [sid] => ***************************
                                )

                            [uri:protected] => /Accounts/***************************.json
                        )

                    [_addresses:protected] => 
                    [_applications:protected] => 
                    [_authorizedConnectApps:protected] => 
                    [_availablePhoneNumbers:protected] => 
                    [_balance:protected] => 
                    [_calls:protected] => 
                    [_conferences:protected] => 
                    [_connectApps:protected] => 
                    [_incomingPhoneNumbers:protected] => 
                    [_keys:protected] => 
                    [_messages:protected] => 
                    [_newKeys:protected] => 
                    [_newSigningKeys:protected] => 
                    [_notifications:protected] => 
                    [_outgoingCallerIds:protected] => 
                    [_queues:protected] => 
                    [_recordings:protected] => 
                    [_signingKeys:protected] => 
                    [_sip:protected] => 
                    [_shortCodes:protected] => 
                    [_tokens:protected] => 
                    [_transcriptions:protected] => 
                    [_usage:protected] => 
                    [_validationRequests:protected] => 
                    [domain:protected] => Twilio\Rest\Api Object
                        (
                            [_v2010:protected] => Twilio\Rest\Api\V2010 Object
 *RECURSION*
                            [client:protected] => Twilio\Rest\Client Object
                                (
                                    [username:protected] => ***************************
                                    [password:protected] => ***************************
                                    [accountSid:protected] => ***************************
                                    [region:protected] => 
                                    [edge:protected] => 
                                    [httpClient:protected] => Twilio\Http\CurlClient Object
                                        (
                                            [curlOptions:protected] => Array
                                                (
                                                )

                                            [debugHttp:protected] => 
                                            [lastRequest] => Array
                                                (
                                                    [10002] => https://api.twilio.com/2010-04-01/Accounts/***************************/Calls.json?PageSize=1
                                                    [42] => 1
                                                    [19913] => 1
                                                    [14] => 
                                                    [10023] => Array
                                                        (
                                                            [0] => User-Agent: twilio-php/6.9.0 (PHP 7.3.26)
                                                            [1] => Accept-Charset: utf-8
                                                            [2] => Accept: application/json
                                                            [3] => Authorization: Basic ***************************==
                                                        )

                                                    [13] => 60
                                                    [80] => 1
                                                )

                                            [lastResponse] => Twilio\Http\Response Object
                                                (
                                                    [headers:protected] => Array
                                                        (
                                                            [Date] =>  Tue, 19 Jan 2021 10:20:01 GMT
                                                            [Content-Type] =>  application/json; charset=utf-8
                                                            [Content-Length] =>  1650
                                                            [Connection] =>  keep-alive
                                                            [Twilio-Concurrent-Requests] =>  1
                                                            [Twilio-Request-Id] =>  ***************************
                                                            [Twilio-Request-Duration] =>  0.063
                                                            [Access-Control-Allow-Origin] =>  *
                                                            [Access-Control-Allow-Headers] =>  Accept, Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since
                                                            [Access-Control-Allow-Methods] =>  GET, POST, DELETE, OPTIONS
                                                            [Access-Control-Expose-Headers] =>  ETag
                                                            [Access-Control-Allow-Credentials] =>  true
                                                            [X-Powered-By] =>  AT-5000
                                                            [X-Shenanigans] =>  none
                                                            [X-Home-Region] =>  us1
                                                            [X-API-Domain] =>  api.twilio.com
                                                            [Strict-Transport-Security] =>  max-age=31536000
                                                        )

                                                    [content:protected] => {"first_page_uri": "/2010-04-01/Accounts/***************************/Calls.json?PageSize=1&Page=0", "end": 0, "calls": [{"sid": "***************************", "date_created": "Thu, 17 Dec 2020 13:06:51 +0000", "date_updated": "Thu, 17 Dec 2020 13:08:13 +0000", "parent_call_sid": "***************************", "account_sid": "***************************", "to": "+44XXXXXXXXX", "to_formatted": "+44XXXXXXXXX", "from": "+44XXXXXXXXX", "from_formatted": "+44XXXXXXXXX", "phone_number_sid": "***************************", "status": "completed", "start_time": "Thu, 17 Dec 2020 13:06:59 +0000", "end_time": "Thu, 17 Dec 2020 13:08:13 +0000", "duration": "74", "price": "-0.04489", "price_unit": "GBP", "direction": "outbound-dial", "answered_by": null, "annotation": null, "api_version": "2010-04-01", "forwarded_from": "", "group_sid": null, "caller_name": null, "queue_time": "0", "trunk_sid": "", "uri": "/2010-04-01/Accounts/***************************/Calls/***************************.json", "subresource_uris": {"notifications": "/2010-04-01/Accounts/***************************/Calls/***************************/Notifications.json", "recordings": "/2010-04-01/Accounts/***************************/Calls/***************************/Recordings.json"}}], "previous_page_uri": null, "uri": "/2010-04-01/Accounts/***************************/Calls.json?PageSize=1&Page=0", "page_size": 1, "start": 0, "next_page_uri": "/2010-04-01/Accounts/***************************/Calls.json?PageSize=1&Page=1&PageToken=PA***************************", "page": 0}
                                                    [statusCode:protected] => 200
                                                )

                                        )

                                    [environment:protected] => Array
                                        (
                                            [CONTEXT_DOCUMENT_ROOT] => /home/sites/***************************/public_html/
                                            [CONTEXT_PREFIX] => 
                                            [DEFAULT_PHP_VERSION] => 56
                                            [DOCUMENT_ROOT] => /home/sites/***************************/public_html/
                                            [GATEWAY_INTERFACE] => CGI/1.1
                                            [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
                                            [HTTP_ACCEPT_LANGUAGE] => en
                                            [HTTP_AUTHORIZATION] => 
                                            [HTTP_CACHE_CONTROL] => max-age=0
                                            [HTTP_CDN_LOOP] => StackCDN
                                            [HTTP_COOKIE] => _ga=GA1.3.1978579865.1577088649; PHPSESSID=edc6270285aae3adbd578e93364ae4e8; tk_tc=1h6tdqAaD%2BrqyqPB
                                            [HTTP_HOST] => *****************
                                            [HTTP_PS_CAPABILITYLIST] => ll,ii,dj,jw,wa,ws
                                            [HTTP_STACKCDN_CONNECTING_IP] => 62.31.255.146
                                            [HTTP_UPGRADE_INSECURE_REQUESTS] => 1
                                            [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36
                                            [HTTP_X_ASN] => 5089
                                            [HTTP_X_BALANCED_HOST] => ***********
                                            [HTTP_X_CAPTCHA_IP] => 62.31.255.146
                                            [HTTP_X_COUNTRY] => GB
                                            [HTTP_X_FORWARDED_FOR] => 62.31.255.146
                                            [HTTP_X_SERVICE_LEVEL] => standard
                                            [HTTP_X_TARGET_DC] => portal
                                            [PATH] => /bin:/usr/bin:/usr/php53/usr/bin:/usr/php54/usr/bin:/usr/php55/usr/bin:/usr/php56/usr/bin:/usr/php70/usr/bin:/usr/php71/usr/bin:/usr/php72/usr/bin:/usr/php73/usr/bin:/usr/php74/usr/bin:/usr/php80/bin
                                            [QUERY_STRING] => 
                                            [REDIRECT_STATUS] => 200
                                            [REMOTE_ADDR] => 62.31.255.146
                                            [REMOTE_PORT] => 59810
                                            [REQUEST_METHOD] => GET
                                            [REQUEST_SCHEME] => http
                                            [REQUEST_URI] => /pd/chart-new.php
                                            [SCRIPT_FILENAME] => /home/sites/***************************/public_html/pd/chart-new.php
                                            [SCRIPT_NAME] => /pd/chart-new.php
                                            [SCRIPT_URI] => ***************************
                                            [SCRIPT_URL] => /pd/chart-new.php
                                            [SERVER_ADDR] => 127.0.0.1
                                            [SERVER_ADMIN] => your hosting provider
                                            [SERVER_NAME] => ************8
                                            [SERVER_PORT] => 80
                                            [SERVER_PROTOCOL] => HTTP/1.1
                                            [SERVER_SIGNATURE] => 
                                            [SERVER_SOFTWARE] => Apache
                                            [UNIQUE_ID] => YAayULtz@eAIbUu2HBJX8QAAAAI
                                            [USERNAME_REAL] => 13d6aa4912
                                            [stackSUPHPpath] => /etc/suphp.conf
                                        )

                                    [_account:protected] => 
                                    [_accounts:protected] => 
                                    [_api:protected] => Twilio\Rest\Api Object
 *RECURSION*
                                    [_autopilot:protected] => 
                                    [_chat:protected] => 
                                    [_conversations:protected] => 
                                    [_fax:protected] => 
                                    [_flexApi:protected] => 
                                    [_insights:protected] => 
                                    [_ipMessaging:protected] => 
                                    [_lookups:protected] => 
                                    [_messaging:protected] => 
                                    [_monitor:protected] => 
                                    [_notify:protected] => 
                                    [_numbers:protected] => 
                                    [_preview:protected] => 
                                    [_pricing:protected] => 
                                    [_proxy:protected] => 
                                    [_serverless:protected] => 
                                    [_studio:protected] => 
                                    [_sync:protected] => 
                                    [_taskrouter:protected] => 
                                    [_trunking:protected] => 
                                    [_verify:protected] => 
                                    [_video:protected] => 
                                    [_voice:protected] => 
                                    [_wireless:protected] => 
                                    [_supersim:protected] => 
                                    [_bulkexports:protected] => 
                                )

                            [baseUrl:protected] => https://api.twilio.com
                        )

                    [version:protected] => 2010-04-01
                )

            [context:protected] => 
            [properties:protected] => Array
                (
                    [sid] => ***************************
                    [dateCreated] => DateTime Object
                        (
                            [date] => 2020-12-17 13:06:51.000000
                            [timezone_type] => 1
                            [timezone] => +00:00
                        )

                    [dateUpdated] => DateTime Object
                        (
                            [date] => 2020-12-17 13:08:13.000000
                            [timezone_type] => 1
                            [timezone] => +00:00
                        )

                    [parentCallSid] => ***************************
                    [accountSid] => ***************************
                    [to] => +44XXXXXXXXX
                    [toFormatted] => +44XXXXXXXXX
                    [from] => +44XXXXXXXXX
                    [fromFormatted] => +44XXXXXXXXX
                    [phoneNumberSid] => ***************************
                    [status] => completed
                    [startTime] => DateTime Object
                        (
                            [date] => 2020-12-17 13:06:59.000000
                            [timezone_type] => 1
                            [timezone] => +00:00
                        )

                    [endTime] => DateTime Object
                        (
                            [date] => 2020-12-17 13:08:13.000000
                            [timezone_type] => 1
                            [timezone] => +00:00
                        )

                    [duration] => 74
                    [price] => -0.04489
                    [priceUnit] => GBP
                    [direction] => outbound-dial
                    [answeredBy] => 
                    [annotation] => 
                    [apiVersion] => 2010-04-01
                    [forwardedFrom] => 
                    [groupSid] => 
                    [callerName] => 
                    [queueTime] => 0
                    [trunkSid] => 
                    [uri] => /2010-04-01/Accounts/***************************/Calls/***************************.json
                    [subresourceUris] => Array
                        (
                            [notifications] => /2010-04-01/Accounts/***************************/Calls/***************************/Notifications.json
                            [recordings] => /2010-04-01/Accounts/***************************/Calls/***************************/Recordings.json
                        )

                )

            [solution:protected] => Array
                (
                    [accountSid] => ***************************
                    [sid] => ***************************
                )

        )

)

标签: phparrays

解决方案


您可以使用array_reduce函数作为方法:

$result = array_reduce(
    $calls,
    function($res, $call) {
        $start = date_format($call->startTime, 'Y-m-d');
        if (isset($res[$start])) $res[$start]++; else $res[$start] = 1;
        return $res;
    },
    []
);

print_r($result);

在这里尝试PHP


推荐阅读