![](/img/trans.png)
[英]PHP Create new array from existing array with some maths calculation on new array [multidimensional]
[英]Create new array from a multidimensional if some values are similar in php?
我有一個像下面這樣的數組
Array (
[0] => Array ( [subj_title] => A, [value] => 0 )
[1] => Array ( [subj_title] => B, [value] => 30 )
[2] => Array ( [subj_title] => C, [value] => 6 )
[3] => Array ( [subj_title] => C, [value] => 8 )
[4] => Array ( [subj_title] => C, [value] => 5 )
[5] => Array ( [subj_title] => C, [value] => 11 )
)
我希望這個數組如下所示
Array (
[0] => Array ( [subj_title] => A, [value] => 0 )
[1] => Array ( [subj_title] => B, [value] => 30 )
[2] => Array ( [subj_title] => C, [value] => 30 ) //Sum of value C
)
試圖找到最簡單的方法來做到這一點,我有點搞砸了我的代碼。 請參考作品
$old_subj_title = $subj_title = '';
$j_subjects = $j_subject = [];
foreach($subjects_display as $r) {
$subj_title = !empty($r->subj_title) ? $r->subj_title : '';
if(!empty($subj_title) && $old_subj_title != $subj_title) {
$j_subject['subj_title'] = $subj_title;
$j_subject['value'] = $r->marks;
}
if($old_subj_title == $subj_title) {
//something can be done
}
$j_subjects[] = $j_subject;
$old_subj_title = $subj_title;
}
print_r($j_subjects);
Output:
Array (
[0] => Array ( [subj_title] => A, [value] => 0 )
[1] => Array ( [subj_title] => B, [value] => 30 )
[2] => Array ( [subj_title] => C, [value] => 6 ) //Single entry of same title
)
你可以試試下面的代碼
$data = array (
array ('subj_title' => 'A', 'value' => 0 ) ,
array ('subj_title' => 'B', 'value' => 30 ) ,
array ('subj_title' => 'C', 'value' => 6 ) ,
array ('subj_title' => 'C', 'value' => 8 ) ,
array ('subj_title' => 'C', 'value' => 5 ),
array ('subj_title' => 'C', 'value' => 11 )
);
$result = array();
foreach($data as $key => $value){
$index = $value['subj_title'];
// Create a new sub array with key as subj_title
if(!isset($result[$index])){
$result[$index]['subj_title'] = $value['subj_title'];
$result[$index]['value'] = $value['value'];
}else{
// If subarray already exists then values get added
$result[$index]['value'] = $result[$index]['value'] + $value['value'];
}
}
$result = array_values($result);
echo '<pre>';
print_r($result);
如果您使用 SQL 查詢獲取數據,您可以使用 GROUP BY 直接從數據庫中獲取結果,如下所示
SELECT subj_title, SUM(value) as value FROM yourTable
GROUP BY subj_title
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.