Cluster PHP messages array

134 views Asked by At

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?

3

There are 3 answers

0
Eineki On BEST ANSWER

If you want to get an array with all the code in the input array you can use a simple mapping function:

function mapping($x) { 
    return $x['code'];
}

$codes = array_map(mapping, $ar);

or as one liner:

$codes = array_map(function($x) { return $x['code'];}, $ar);

Once you have it, I think it is straightforward to implement a complete solution.

Maybe a function like this:

function groupCodes($ar) {
  return array (
    'message'=> $ar[0]['message'],
    'code' => array_map(function($x) { return $x['code'];}, $ar)
  );
}

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

2
deceze On
$result = [];
foreach ($ar as $item) {
    $result[$item['message']][] = $item['code'];
}

$result = array_map(
    function ($message, $code) { return compact('message', 'code'); },
    array_keys($result),
    $result
);
2
Jonathan On

You will need to group them together using the comment element which is the message.

$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;

$grouped = [];

foreach($ar as $row) {
    $grouped[$row['message']]['message'] = $row['message'];
    $grouped[$row['message']]['code'][] = $row['code'];
}

$ar = array_values($grouped);