Reputation: 493
I'd like to merge duplicated array values based on the author_id
into one. My code is as follows:
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
);
}
}
Multi-dimensional array looks like this:
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
)
)
When there's an identical author id, I'd like to combine the array into something like this:
[4] => Array
(
[author_id] => 27
[product_id] => array( 166, 331)
[sales] => array(6, 6)
)
Any guidance is much appreciated.
Upvotes: 0
Views: 357
Reputation: 11642
You can change the for-loop
in full_array
function to do something like that:
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]);
}
}
If you don't want the keys (author ID) in the result array just use array-values
Upvotes: 3