1
我具有低於$test
陣列array_reduce使用動態變量傳遞在第二功能
Array
(
[0] => Array
(
[quantity] => 3
[stock_id] => _PHONE
)
[1] => Array
(
[quantity] => 3
[stock_id] => 102
)
[2] => Array
(
[quantity] => 4
[stock_id] => _PHONE
)
[3] => Array
(
[quantity] => 3
[stock_id] => 102
)
[4] => Array
(
[quantity] => 4
[stock_id] => _PHONE
)
[5] => Array
(
[quantity] => 6
[stock_id] => _PHONE
)
[6] => Array
(
[quantity] => 2
[stock_id] => 102
)
)
和總結相同STOCK_ID鍵之一,我用下面的功能:
function sum($array, $key){
isset($array[$key['stock_id']]) ? $array[$key['stock_id']]['quantity'] += $key['quantity'] : $array[$key['stock_id']] = $key;
return $array;
};
//merge same stock_id and sum the quantity same stock id
$sum_same_stock_id = array_reduce($test, "sum");
,結果順利如下圖所示:
$ sum_same_stock_id:
Array
(
[_PHONE] => Array
(
[quantity] => 17
[stock_id] => _PHONE
)
[102] => Array
(
[quantity] => 8
[stock_id] => 102
)
)
所以這裏的問題是,我想通過一個動態的鍵值不只是固定值stock_id
& quantity
在sum
函數上面。嘗試了各種方法,但仍然無法想通。我們可以把這些功能放入課堂嗎?
任何意見是讚賞!
'索引'0'處的stock_id'和'1'處的'數量'索引將保持相同嗎? – Noman
不,例如,如果起始數組中的stock_id和數量名稱已更改爲「數量」和「庫存代碼」等不同名稱。然後在求和函數中,我只需要輸入類似於函數和($ array,$ key,$ amount,$ id)的動態變量,其中$ amount和$ id是「amount」和「stock_code」的名稱,而不是手動在「總和」功能中重複替換「金額」和「股票代碼」。 – SonDang
@SonDang,你見過我的回答嗎? – splash58