I have the following situation, I am receiving messages in an array like this:
$ar[0]['message'] = "TEST MESSAGE 1";
$ar[0]['code'] = 566666;
$ar[1]['message'] = "TEST MESSAGE 1";
$ar[1]['code'] = 255555;
$ar[2]['message'] = "TEST MESSAGE 1";
$ar[2]['code'] = 256323;
As you can see, the code's are different, but the messages are the same.
That given, I know that that the messages will stay the same, but I need to cluster the code's into 1 array, how would I go to do that about that one?
Please bear in mind that I am actually doing a foreach loop on alot of messages like this.
foreach( $ar as $array ){}
So I have to sortoff 'cluster' the messages, the output I need is like this:
$ar[0]['message'] = "TEST MESSAGE 1";
$ar[0]['code'] = array( 566666, 255555, 256323 );
Can anybody guide me in the right way?
If you want to get an array with all the code in the input array you can use a simple mapping function:
or as one liner:
Once you have it, I think it is straightforward to implement a complete solution.
Maybe a function like this:
This function takes the message from the first element of your array and groups the codes from all the elements into a resulting array.
If you want to filter code toward the messages you can leverage array_filter, or use a simple if in your mapping closure.
References:
http://php.net/manual/en/function.array-map.php
http://php.net/manual/en/function.array-filter.php