簡體   English   中英

結合類似的數據 - PHP中的數組

[英]Combining Similar Data - Arrays in PHP

我有一個2d數組,如下所示:

1月1日,10日
1月2日,20日
1月2日,15日
1月3日,20日
1月3日,10日
1月3日,5日

我需要創建一種掃描此數組的方法,並將類似日期的數字添加到新數組中,以便:

1月1日,10日
1月2日,35日
1月3日,35日

實現這一目標的最快方法是什么? 謝謝!

嘗試這個

<?php

// array of monthdate structure
$monthdate = array();
$monthdate[] = array('date'=>'Jan 1','num'=>10);
$monthdate[] = array('date'=>'Jan 2','num'=>20);
$monthdate[] = array('date'=>'Jan 2','num'=>15);    
$monthdate[] = array('date'=>'Jan 3','num'=>20);
$monthdate[] = array('date'=>'Jan 3','num'=>10);             
// begin the iteration for grouping date and calculate the num
$sumofnum = array();
foreach($monthdate as $month) {
    $index = month_exists($month['date'], $sumofnum);
    if ($index < 0) {
        $sumofnum[] = $month;
    }
    else {
        $sumofnum[$index]['num'] +=  $month['num'];
    }
}
print_r($sumofnum); //display 

// for search if a monthdate has been added into $sumofnum, returns the key (index)
function month_exists($monthname, $array) {
    $result = -1;
    for($i=0; $i<sizeof($array); $i++) {
        if ($array[$i]['date'] == $monthname) {
            $result = $i;
            break;
        }
    }
    return $result;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM