我是一名PHP初學者,整天都在尋找解決方案,但沒有成功。如何結合多維數組中的數組和計數值?
我有以下的數組:
$data = Array
(
[0] => Array
(
[my_id] => 1
[my_post_id] => 123
[my_status] => 1
[my_rating] => 5
)
[1] => Array
(
[my_id] => 2
[my_post_id] => 123
[my_status] => 1
[my_rating] => 4
)
[2] => Array
(
[my_id] => 3
[my_post_id] => 123
[my_status] => 1
[my_rating] => 5
)
[3] => Array
(
[my_id] => 4
[my_post_id] => 456
[my_status] => 1
[my_rating] => 5
)
[4] => Array
(
[my_id] => 5
[my_post_id] => 456
[my_status] => 1
[my_rating] => 3
)
)
,想用相同的「my_post_id」合併數組和計數「my_status」和「my_rating」,其具有相同的「my_post_id」的值。
最後,我想有以下數組:
$data = Array
(
[0] => Array
(
[my_post_id] => 123
[my_status] => 3
[my_rating] => 14
)
[1] => Array
(
[my_post_id] => 456
[my_status] => 2
[my_rating] => 8
)
)
我能得到獨特的「my_post_id」陣列,下面的代碼,但我無法找出如何計算其他值。
$out = array();
foreach($data as $row) {
$out[$row['my_post_id']] = $row;
}
$array = array_values($out);
任何幫助將不勝感激。
丹尼爾
我我確信你可以用'if(i sset($ out [$ row ['my_post_id']])){...}' –
仍然不明白你的'merge'是如何工作的... – Baba
看看MiDo和我的帖子在下面。兩者都向您展示增加(總和)值的方法。唯一真正的區別是他將post_id作爲關鍵字段,而我的增量則像你所要求的那樣不相關。我認爲如果你重新考慮你的要求,他對你的最終結果更有意義。 – Dave