2017-02-21 89 views
1

有一個這樣的數組:PHP多維數組:將通過項,並添加值的另一個關鍵

array (
    '@attributes' => 
    array (
    'status' => 'ok', 
), 
    'time_entries' => 
    array (
    '@attributes' => 
    array (
     'page' => '1', 
     'per_page' => '100', 
     'pages' => '1', 
     'total' => '33', 
    ), 
    'time_entry' => 
    array (
     0 => 
     array (
     'time_entry_id' => '1411884', 
     'staff_id' => '22384', 
     'project_id' => '11116', 
     'task_id' => '3296', 
     'hours' => '1.75', 
     'date' => '2017-02-20', 
     'notes' => 'What is Quadra, Events Slider, Event Page Setup', 
     'billed' => '0', 
    ), 
     1 => 
     array (
     'time_entry_id' => '1411254', 
     'staff_id' => '22384', 
     'project_id' => '11116', 
     'task_id' => '3296', 
     'hours' => '1.5', 
     'date' => '2017-02-17', 
     'notes' => 'Events Slider, Background overlay, Intro', 
     'billed' => '0', 
    ), 
     2 => 
     array (
     'time_entry_id' => '1410694', 
     'staff_id' => '22384', 
     'project_id' => '11116', 
     'task_id' => '3296', 
     'hours' => '2.75', 
     'date' => '2017-02-16', 
     'notes' => 'Background Image SVGs, Header, Footer', 
     'billed' => '0', 
    ), 
     3 => 
     array (
     'time_entry_id' => '1410586', 
     'staff_id' => '22384', 
     'project_id' => '11116', 
     'task_id' => '3296', 
     'hours' => '0.5', 
     'date' => '2017-02-15', 
     'notes' => 'Site Background 
Assign Less Variables', 
     'billed' => '0', 
    ), 
     4 => 
     array (
     'time_entry_id' => '1409621', 
     'staff_id' => '22384', 
     'project_id' => '11116', 
     'task_id' => '3296', 
     'hours' => '0.25', 
     'date' => '2017-02-14', 
     'notes' => 'Theme Install', 
     'billed' => '0', 
    ), 

...它實際上推移進一步比第一4.我所希望做的是排序這些數組通過鍵[「task_id」],以便我可以將它們組合在一起,然後將[「小時」]鍵加在一起 ​​- 以便最後我可以輸出在每個task_id下工作的總小時數。

我試了一下'array_merge_recursive'和類似的,但我很茫然;這是PHP高於我的水平。非常感謝幫助。

+1

您可以替換'var_dump'用'var_export' – RiggsFolly

+1

要以不同的方式說明RiggsFolly的評論,您發佈的數組格式爲var_dump的輸出格式,不能複製並粘貼到php中。如果您使用var_export並將其輸出,那麼人們可以更輕鬆地爲您提供幫助。 –

+0

我做var_dump var_export switcheroo ... –

回答

1

所以你的小時數的順序對結果進行排序'可能會更好地通過生成一組新數據而不是嘗試修改這個數組來完成一個組和總和。

像這樣的東西會給你你在找什麼:

$time_entries = $your_array["time_entries"]["time_entry"]; 
$task_hours = []; 
foreach ($time_entries as $time_entry) { 
    if (!isset($task_hours[$time_entry["task_id"]])) { 
     $task_hours[$time_entry["task_id"]] = 0; 
    } 
    $task_hours[$time_entry["task_id"]] += (float) $time_entry["hours"]; 
} 

$task_hours會給你一個值,如:

Array 
(
    [3296] => 5 
    [1879] => 0.25 
) 
0

不是對數組進行排序,然後總結小時數,爲什麼不對數組的相關部分進行處理,並且一次性進行求和。

$tots = array(); 
foreach($array['time_entry'] as $task) { 
    if (isset($tots['task_id'])) { 
     $tots['task_id'] += $task['hours']; 
    } else { 
     $tots['task_id'] = $task['hours']; 
    } 
} 

你現在應該有一個數組,其中的關鍵是task_id和它的價值是所有鍵hours的總和。

如果你想在訂單task_id的那麼$tots陣列outputing任何結果

ksort($tots); 

之前,如果你想在

asort($tots);