phparray-unique

array_unique in php with subarray in array


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));

Solution

  • 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);