数组中的唯一数组

时间:2014-04-03 09:44:55

标签: php arrays multidimensional-array unique

我有这个数组

Array
    (
        [0] => Array
            (

                [id] => book
                [name] => Array
                    (
                        [0] => author
                        [1] => title
                        [2] => genre
                        [3] => price
                        [4] => publish_date
                        [5] => description
                    )

            )

        [1] => Array
            (
                [id] => book
                [name] => Array
                    (
                        [0] => author
                        [1] => title
                        [2] => genre
                        [3] => price
                        [4] => publish_date
                        [5] => description
                    )

            )

    )
    Array
    (
        [0] => Array
            (
                [id] => library
                [name] => Array
                    (
                        [0] => room
                        [1] => room
                    )

            )

        [1] => Array
            (
                [id] => library
                [name] => Array
                    (
                        [0] => book
                        [1] => book
                        [2] => book
                        [3] => book
                   )   
            )  
    )

我希望我的输出看起来像

Array
    (
        [0] => Array
            (
                [id] => library
                [name] => Array
                     (
                        [0] => room
                        [1] => room
                    )
                     (
                        [0] => book
                        [1] => book
                        [2] => book
                        [3] => book
                    )

            )

    )
    Array
    (
    [0] => Array
    (

                [id] => book
                [name] => Array
                    (
                        [0] => author
                        [1] => title
                        [2] => genre
                        [3] => price
                        [4] => publish_date
                        [5] => description
                    )

            )
    }

我正在努力比较所有的id和名字 如果它具有相同的id,那么它将所有值[name]放在一起 如果它具有相同的名称,并且相同的ID唯一 非常感谢 我试图这样做,但它只返回只有唯一的ID,它有警告: 未定义的索引:名称

if (is_array($servico))
{
    foreach($servico as $data)
    {                              
        $result[$data['id']][] =  ($data['name']);                             
    }
}

1 个答案:

答案 0 :(得分:0)

在添加元素之前,您需要检查新元素是否已经在数组中,这样您才能获得唯一元素。并且为了防止关于未定义索引的警告,如果元素尚不存在,则需要初始化该元素。

foreach ($servico as $data) {
    if (!isset($result[$data['id']])) {
        $result[$data['id']] = array();
    }
    if (!in_array($data['name'], $result[$data['id']])) {
        $result[$data['id']][] = $data['name'];
    }
}