2

I've been struggling with this issue for the past couple of days now. I've looked around StackOverflow but have only encountered topics where the solution relies on all the keys in the multidimensional array are the same.

My issue is merging a multidimensional array based on a similar key and value.

Current Output:

Array ( 
    [0] => Array ( 
        [y] => 2015-10-17 [c] => 1 
    ) 
    [1] => Array ( 
        [y] => 2015-10-17 [b] => 1 
    ) 
    [2] => Array (
        [y] => 2015-10-17 [d] => 1 
    ) 
    [3] => Array ( 
        [y] => 2015-10-17 [a] => 6 
    ) 
    [4] => Array ( 
        [y] => 2015-10-18 [e] => 2 
    ) 
    [5] => Array ( 
        [y] => 2015-10-18 [c] => 1 
    ) 
    [6] => Array ( 
        [y] => 2015-10-18 [b] => 1 
    ) 
    [7] => Array ( 
        [y] => 2015-10-20 [c] => 1 
    ) 
    [8] => Array ( 
        [y] => 2015-10-20 [b] => 2 
    ) 
)

Desired Output:

Array ( 
    [0] => Array ( 
        [y] => 2015-10-17 [c] => 1 [b] => 1 [d] => 1 [a] => 6 
    ) 
    [1] => Array ( 
        [y] => 2015-10-18 [e] => 2 [c] => 1 [b] => 1 
    ) 
    [2] => Array ( 
        [y] => 2015-10-20 [c] => 1 [b] => 2 
    ) 
)
4
  • What do the original arrays look like? We can't tell you how to convert them if we don't have any idea what they look like. Commented Oct 20, 2015 at 15:19
  • The original array is posted above under Current Output: , and the desired output is below? Sorry if I messed something upp? Commented Oct 20, 2015 at 15:24
  • You didn't mess anything up. But I am struggling to see exactly how the first changed into the second there. All algorithms require some pattern of automation and I do not see one there. It looks as though it was arbitrarily, manually edited. Can you elaborate more please? Commented Oct 20, 2015 at 15:25
  • Never mind. I just noticed that they were grouped by dates. Should not be too hard. I will work on it tomorrow if no one has answered by then. Commented Oct 20, 2015 at 15:28

1 Answer 1

1

Create a result array with the date as the key. If it exists merge it. Then use array_values() to re-index the result:

foreach($array as $value) {
    if(isset($result[$value['y']])) {
        $result[$value['y']] = array_merge($result[$value['y']], $value);
    } else {
        $result[$value['y']] = $value;
    }
}
$result = array_values($result);
Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm. Lifesaver mate. (Y) Thanks for the explanation as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.