0

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.

1
  • Do you need to keep the original numeric array key? If not, I would use the author_id as key, then you can easily “look up” whether an entry for an id already exists in your $products array using isset. Otherwise you will have to search the array for an entry with that author_id first. (It might make sense to have the product_id and sales be arrays in any case, so for your second item with author_id 25 that would then be [product_id] => array(331) and [sales] => array(6) - usually easier to work with such data if the format is consistent.) Commented Jan 21, 2019 at 11:25

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

This is a better answer than mine. Didn't notice the code created the array.
Perfect! Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.