PHP Removing duplicate objects from array

后端 未结 2 849
面向向阳花
面向向阳花 2020-12-18 11:50

I\'ve tried all sorts of PHP logic and PHP\'s built in functions to remove duplicate values but it is not working no errors shows up but all my JQuery and CSS doesn\'t work

相关标签:
2条回答
  • 2020-12-18 12:17

    You can make it unique for any field (key) like id, name or num

    function unique_multidimensional_array($array, $key) {
        $temp_array = array();
        $i = 0;
        $key_array = array();
    
        foreach($array as $val) {
            if (!in_array($val[$key], $key_array)) {
                $key_array[$i] = $val[$key];
                $temp_array[$i] = $val;
            }
            $i++;
        }
        return $temp_array;
    }
    
    0 讨论(0)
  • 2020-12-18 12:29

    try the following code

    function my_array_unique($array, $keep_key_assoc = false){
        $duplicate_keys = array();
        $tmp = array();       
    
        foreach ($array as $key => $val){
            // convert objects to arrays, in_array() does not support objects
            if (is_object($val))
                $val = (array)$val;
    
            if (!in_array($val, $tmp))
                $tmp[] = $val;
            else
                $duplicate_keys[] = $key;
        }
    
        foreach ($duplicate_keys as $key)
            unset($array[$key]);
    
        return $keep_key_assoc ? $array : array_values($array);
    }
    
    0 讨论(0)
提交回复
热议问题