简体   繁体   中英

Cluster PHP messages array

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?

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM