problem with array_unique variation

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • adamalton
    New Member
    • Feb 2007
    • 93

    problem with array_unique variation

    I've got a multi-dimensional array that I'm trying to remove duplicate rows from. Like this:
    [PHP]
    $arr[]=array('biscuit ','cheese','cow ');
    $arr[]=array('biscuit ','cheese','hor se');
    $arr[]=array('biscuit ','cheese','hor se');
    $arr[]=array(7,42,10) ;
    $arr[]=array(7,34,10) ;
    $arr[]=array(7,42,10) ;
  • adamalton
    New Member
    • Feb 2007
    • 93

    #2
    Dammit, that didn't post properly. Should have been this:

    I've got a multi-dimensional array that I'm trying to remove duplicate rows from. Like this:
    [PHP]
    $arr[]=array('biscuit ','cheese','cow ');
    $arr[]=array('biscuit ','cheese','hor se');
    $arr[]=array('biscuit ','cheese','hor se');
    $arr[]=array(7,42,10) ;
    $arr[]=array(7,34,10) ;
    $arr[]=array(7,42,10) ; [/PHP]

    I'm trying to delete rows that are IDENTICAL (i.e. delete duplicate arrays), so I would want to delete the 'biscuit,cheese ,horse' array, and the duplicate '7,42,10' array, but not any of the others because I only want to delete if the entire row is an identical duplicate.

    The array_unique function doesn't deal with multi-dimensional arrays, so I wrote some code that would (or should have!) done the job. I can't for the life of me work out why it doesn't work.

    [PHP]
    for($i=0; $i<($num_of_arr ays-1); $i++) //-1 because when you get to the last one there's no others to compare it to
    {
    for($j=$i+1; $j<$num_of_arra ys; $j++)
    //$j is 1 more than $i, so that you start by comparing the NEXT row to the current one
    {
    $num_elements=c ount($arr[$i]);
    for($k=0; $k<$num_element s; $k++)
    {
    if($arr[$i][$k] != $arr[$j][$k])
    //if any of the values are NOT the same
    {
    $abort="yes";
    }
    }
    if(!$abort)
    unset($arr[$j]);
    }
    }

    //this bit just re-arranges the keys so that there aren't any empty rows
    foreach (array_keys($ar r) as $key)
    {
    if($arr[$key]) //if the element exists
    $temp[]=$arr[$key];
    }
    $arr=$temp;[/PHP]

    Comment

    Working...