[英]Merge key values in a multidimensional array php
我想將基於author_id
重復數組值合並為一個。 我的代碼如下:
public function full_array( $date_query, $minimum ) {
$data = $this->date_array_freqency( $date_query, $minimum );
$products = array();
foreach( $data as $id => $sales ) {
$products[] = array (
'author_id' => get_post_field( 'post_author', $id ),
'product_id' => $id,
'sales' => $sales
);
}
}
多維數組如下所示:
Array
(
....
[4] => Array
(
[author_id] => 27
[product_id] => 166
[sales] => 6
)
[5] => Array
(
[author_id] => 25
[product_id] => 1056
[sales] => 6
)
[6] => Array
(
[author_id] => 27
[product_id] => 331
[sales] => 6
)
)
當存在相同的作者ID時,我想將數組組合成如下形式:
[4] => Array
(
[author_id] => 27
[product_id] => array( 166, 331)
[sales] => array(6, 6)
)
任何指導是非常感謝。
您可以更改full_array
函數中的for-loop
來執行以下操作:
foreach( $data as $id => $sales ) {
$aId = get_post_field( 'post_author', $id );
if (isset($products[$aId])) { // if the author already in the result just add the data
$products[$aId]["product_id"][] = $id;
$products[$aId]["sales"][] = $sales;
} else { // if not exist add new data
$products[$aId] = array('author_id' => $aId, 'product_id' => [$id], 'sales' => [$sales]);
}
}
如果您不希望結果數組中的鍵(作者ID),請使用數組值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.