首頁  >  文章  >  後端開發  >  如何按列對二維數組行進行分組並對另一列求和?

如何按列對二維數組行進行分組並對另一列求和?

Barbara Streisand
Barbara Streisand原創
2024-10-27 03:31:03576瀏覽

How to Group 2D Array Rows by Column and Sum Another Column?

按列將二維數組行分組並對另一列求和

根據特定列從二維數組中獲取分組和求和的結果,我們可以採用以下技術:

<code class="php">// Assume we have an array $array containing the data as described in the question.

$ts_by_url = array();

foreach ($array as $data) {
    if (!array_key_exists($data['url_id'], $ts_by_url)) {
        $ts_by_url[$data['url_id']] = 0;
    }
    $ts_by_url[$data['url_id']] += $data['time_spent'];
}</code>

循環遍歷數組並累積$ts_by_url 數組中每個唯一URL ID 所花費的時間。在循環結束時,$ts_by_url 陣列包含分組和求和的結果,其中鍵代表 URL ID,值代表每個 URL ID 所花費的總時間。

範例輸出:

<code class="php">print_r($ts_by_url);
// Output:
// Array
// (
//     [2191238] => 41
//     [2191606] => 240 // == 215 + 25
// )</code>

以上是如何按列對二維數組行進行分組並對另一列求和?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn