remove duplicate value from array with foreach()

Discussion in 'PHP' started by bumbar, Jul 23, 2012.

  1. #1
    Hello!

    I have problem with remove duplicate value from array.

    Value in my case is ... year and month (2012-07, 2012-5 ...) without DAY

    Yes, I know that exist function array_unique(), but do not want so... I want eliminate duplicate value in loop.

    Here is my simple array:

    
    Array
    (
        [0] => Array
            (
                [CAST] => 2012-07-22
            )
    
        [1] => Array
            (
                [CAST] => 2012-07-23
            )
    
        [2] => Array
            (
                [CAST] => 2012-05-04
            )
    
        [3] => Array
            (
                [CAST] => 2012-05-15
            )
    
    )
    
    PHP:
    after foreach I get follow result:

    2012-07-22
    2012-07-23
    2012-05-04
    2012-05-15

    And I wand get this:

    2012-07
    2012-05

    Thank you!
     
    bumbar, Jul 23, 2012 IP
  2. sarahk

    sarahk iTamer Staff

    Messages:
    28,807
    Likes Received:
    4,534
    Best Answers:
    123
    Trophy Points:
    665
    #2
    you can just get the y-m value as you loop through and only reprint the header if it doesn't match the original.

    ie

    
    $ym = '0000-00';
    foreach($arr as $row) {
      if ($ym != substr($row['CAST'],0,7) {
          // do whatever you need to do when the month changes
          $ym = substr($row['CAST'],0,7);
       }
    }
    PHP:
    but if you want to have a useful array I'd do this
    
    $rebuilt = array();
    foreach($arr as $row) {
       $rebuilt[substr($row['CAST'],0,7)] = $row;
    }
    PHP:
    * untested, may have typos

    play around with both doing some echos and var_dumps to see how they give different results.
     
    sarahk, Jul 24, 2012 IP
  3. makebillions2009

    makebillions2009 Greenhorn

    Messages:
    41
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    16
    #3
    Hey,you can try this. it will work$array = array(1, 2, 2, 3);
    $array = array_unique($array); // Array is now (1, 2, 3)
     
    makebillions2009, Jul 24, 2012 IP
  4. sarahk

    sarahk iTamer Staff

    Messages:
    28,807
    Likes Received:
    4,534
    Best Answers:
    123
    Trophy Points:
    665
    #4
    Except that the value that needs to be unique isn't in the array. What s/he has 'Y-m-d' and the uniqueness is based on 'Y-m'
     
    sarahk, Jul 25, 2012 IP
  5. atxsurf

    atxsurf Peon

    Messages:
    2,394
    Likes Received:
    21
    Best Answers:
    1
    Trophy Points:
    0
    #5
    step 1: use foreach to truncate all your dates to yyyy-mm format (e.g. making 2012-07-22 to 2012-07) - by using substr($date, 0, 7) for example
    step 2: use array_unique()
     
    atxsurf, Jul 25, 2012 IP