1

How can i use array_unique function for this array `

$mon  = array('9:00AM - 11:00AM','1:00pm-6pm');
$tue  = array('8:00AM - 11:00AM','12:00pm-6pm');
$wed  = array('9:00AM - 11:00AM','1:00pm-6pm');
$thu  = array('9:00AM - 11:00AM','1:00pm-6pm');
$fri  = array('9:00AM - 12:00PM','1:00pm-6pm');
$sat  = array('9:00AM - 7:00PM');
$sun  = array('9:00AM - 12:00AM','1:00pm-6pm');

$a=array($mon , $tue , $wed , $thu , $fri , $sat , $sun);
print_r(array_unique($a));
Ashutosh Jha
  • 186
  • 1
  • 3
  • 11

3 Answers3

1

You have to write custom function for multi dimensional array, please refer below function

function unique_multidim_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; }

Now, call this function anywhere from your code

 $details = unique_multidim_array($details,'id');

if your case you have to pass key as 0 or 1 like

$a=unique_multidim_array($a,0);
Sanjay
  • 1,958
  • 2
  • 17
  • 25
1

You may use this solution also:

$schedule = array(
    array('9:00AM - 11:00AM','1:00pm-6pm'),
    array('8:00AM - 11:00AM','12:00pm-6pm'),
    array('9:00AM - 11:00AM','1:00pm-6pm'),
    array('9:00AM - 11:00AM','1:00pm-6pm'),
    array('9:00AM - 12:00PM','1:00pm-6pm'),
    array('9:00AM - 7:00PM'),
    array('9:00AM - 12:00AM','1:00pm-6pm'),
);

$schedule = array_map(function ($item) {
    return json_encode($item);
}, $schedule);

// use array_flip to switch keys and values. By doing it the duplicates will be removed    
$json = '[' . implode(',', array_keys(array_flip($schedule))) . ']';
$schedule = json_decode($json);

var_dump($schedule);
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
0

For array_unique(), the PHP manual PHP manual says

Two elements are considered equal if and only if (string) $elem1 === (string) $elem2 i.e. when the string representation is the same, the first element will be used

So internally, each element of the input array is cast to string before comparison. When you have subarrays as elements, casting them to string will output an "Array to string conversion" notice and return a useless result:

var_dump((string)['foo', 'bar']); // string(5) "Array"

Fortunately, building a replacement for array_unique() is easy:

function uniquify(array $arr) {
    return array_reduce(
        $arr,
        function ($carry, $item) {
            if (!in_array($item, $carry)) {
                $carry[] = $item;
            }
            return $carry;
        },
        []
    );
}
Benni
  • 1,023
  • 11
  • 15