1

我有这个数组:

 Array
    (
        [0] => Array
            (
                [id] => new@particip.pl
                [challs] => 
            )

        [1] => Array
            (
                [id] => new@email.pl
                [challs] => 551
            )

        [2] => Array
            (
                [id] => new@email.pl
                [challs] => 551
            )

        [3] => Array
            (
                [id] => new@email.pl
                [challs] => 553
            )

        [4] => Array
            (
                [id] => new@email.pl
                [challs] => 553
            )

        [5] => Array
            (
                [id] => info@mail.com
                [challs] => 
            )

    )

如何使它与唯一的电子邮件地址和加入的 challs 一起排列,例如在这种情况下:

Array
(
    [0] => Array
        (
            [id] => new@particip.pl
            [challs] => 
        )

    [1] => Array
        (
            [id] => new@email.pl
            [challs] => 551, 553
        )


    [2] => Array
        (
            [id] => info@email.com
            [challs] => 
        )

)

可以排序,还是我需要做forach inarray?有人知道怎么做吗?

4

2 回答 2

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);
于 2013-05-16T21:55:26.807 回答
0

我想您想要的是以下内容:

$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);
于 2013-05-16T21:30:59.817 回答