1

I've got this array:

 Array
    (
        [0] => Array
            (
                [id] => [email protected]
                [challs] => 
            )

        [1] => Array
            (
                [id] => [email protected]
                [challs] => 551
            )

        [2] => Array
            (
                [id] => [email protected]
                [challs] => 551
            )

        [3] => Array
            (
                [id] => [email protected]
                [challs] => 553
            )

        [4] => Array
            (
                [id] => [email protected]
                [challs] => 553
            )

        [5] => Array
            (
                [id] => [email protected]
                [challs] => 
            )

    )

How make this to array with unique email addresses and joined challs, for ex in this case:

Array
(
    [0] => Array
        (
            [id] => [email protected]
            [challs] => 
        )

    [1] => Array
        (
            [id] => [email protected]
            [challs] => 551, 553
        )


    [2] => Array
        (
            [id] => [email protected]
            [challs] => 
        )

)

Can be it sorted, or I need to do forach inarray? Someone had idea how to do it?

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
user2213609
  • 73
  • 1
  • 8

2 Answers2

0

I guess something along the line of the following is what you want:

$result = array();

foreach ($arrays as $array) {
    if (! isset($result[$array['id']])) {
        $result[$array['id']] = array(
            'id' => $array['id'],
            'challs' => $array['chall']
        );
    }

    if (! in_array($result[$array['id']]['challs'], $array['chall'])) {
        $result[$array['id']]['challs'] .= ', ' . $array['chall'];
    }
}

$result = array_values($result);
Jan-Henk
  • 4,864
  • 1
  • 24
  • 38
0
$emailsSeen = array();

foreach($array as $key => &$item) {
    if(in_array($item['id'], $emailsSeen) {
        //concatenate 'challs' of repeated email to first occurence of email in $array
        $array[array_search($item['id'], $emailsSeen)]['challs'] .= ', ' . $item['challs'];
        //remove duplicate email item from $array
        unset($array[$key']);
    } else {
        $emailsSeen[$key] = $item['id'];
    }
}

//To reindex the array
$array = array_values($array);
km6zla
  • 4,787
  • 2
  • 29
  • 51