php 2d数组排序与唯一

时间:2013-05-16 21:21:54

标签: php arrays sorting

我有这个阵列:

 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] => 
            )

    )

如何使用唯一的电子邮件地址和加入的聊天来使其成为阵列,例如:

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

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


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

)

可以分类,还是我需要做farch inarray?有人知道怎么做吗?

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);