3v4l.org

run code in 300+ PHP versions simultaneously
<?php $arr = [ '0' => [ 'id' => 34, 'building_id' => 786, 'tenancy_rate' => 0, 'rent_per_room' => 10000, 'management_fee_per_room' => 0, ], '1' => [ 'id' => 35, 'building_id' => 786, 'tenancy_rate' => 10, 'rent_per_room' => 11810, 'management_fee_per_room' => 5400, 'rent' => 86050, ], '2' => [ 'id' => 36, 'building_id' => 786, 'tenancy_rate' => 20, 'rent_per_room' => 11810, 'management_fee_per_room' => 5400, 'rent' => 86050, ], '3' => [ 'id' => 56, 'building_id' => 798, 'tenancy_rate' => 0, 'rent_per_room' => 10000, 'management_fee_per_room' => 5400, 'rent' => 77000, ], '4' => [ 'id' => 57, 'building_id' => 798, 'tenancy_rate' => 10, 'rent_per_room' => 11810, 'management_fee_per_room' => 5400, 'rent' => 86050, ], '5' => [ 'id' => 58, 'building_id' => 798, 'tenancy_rate' => 20, 'rent_per_room' => 11810, 'management_fee_per_room' => 5400, 'rent' => 86050, ], ]; $result = []; foreach ($arr as $val) { // as I see, rate for some array not there, so setting it to 0 $val['rent'] = ($val['rent'] ?? 0); if (isset($result[$val['tenancy_rate']]['rent'])) { $result[$val['tenancy_rate']]['rent'] += $val['rent']; } else { $result[$val['tenancy_rate']] = [ 'tenancy_rate' => $val['tenancy_rate'], 'rent' => $val['rent']]; } } print_r(array_values($result));
Output for 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.27, 8.4.1 - 8.4.14
Array ( [0] => Array ( [tenancy_rate] => 0 [rent] => 77000 ) [1] => Array ( [tenancy_rate] => 10 [rent] => 172100 ) [2] => Array ( [tenancy_rate] => 20 [rent] => 172100 ) )

preferences:
188.15 ms | 408 KiB | 5 Q