How can you make a multidimensional array unique?

后端 未结 6 1187
陌清茗
陌清茗 2020-11-27 08:03

I\'ve got a multidimensional array setup like the following:

array(
  [0]=>
  array(
    [\"name\"]=> \"Foo\"
    [\"slug\"]=> \"Bar\"
  )
  [1]=>         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 08:31

    You can use an associative array.

    $temp_array = array();
    foreach ($array as &$v) {
        if (!isset($temp_array[$v['name']]))
            $temp_array[$v['name']] =& $v;
    }
    

    This creates a temporary array, using $v['name'] as the key. If there is already an element with the same key, it is not added to the temporary array.

    You can convert the associative array back to a sequential array, using

    $array = array_values($temp_array);
    

    Example code and output: http://codepad.org/zHfbtUrl

提交回复
热议问题