Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 26th, 2012  |  syntax: None  |  size: 1.55 KB  |  hits: 17  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. PHP count # of items in an object of a given property value
  2. foreach($items as $item)
  3. {
  4.     if(????) //count of $item->folder_id > 1
  5.        {
  6.          //do something to $item->folder_id=1/$item->item_id=1
  7.        }
  8.  
  9.        elseif(????) // cases where $item->item_id != $item->folder_id
  10.        {
  11.          //do something else to $item->folder_id=1/$item->item_id=2
  12.        }
  13.  
  14.        else
  15.        {
  16.          //do something else to $item->folder_id=2/$item->item_id=3 and folder_id=3/item_id=4
  17.        }
  18. }
  19.        
  20. $totals = array();
  21.  
  22. foreach($items as $item) {
  23.    $totals[$item->folder_id]++;
  24. }
  25.        
  26. $callback = function($item) { return $item->folder_id; };
  27. $result = array_count_values(array_map($callback, $items));
  28.        
  29. array(
  30.     1 => 2,
  31.     2 => 1,
  32.     3 => 1,
  33. );
  34.        
  35. foreach($results as $folder_id => $count) {
  36.     if($count > 1) {
  37.         // There were $count items with folder_id == $folder_id
  38.     }
  39.     // else blah blah
  40. }
  41.        
  42. function count_items(Array $items, $folder_id) {
  43.     return count(array_filter($items,
  44.         function($item) use($folder_id) {
  45.             return $item->folder_id === $folder_id;
  46.         }
  47.      ));
  48. }
  49.        
  50. function folder_count($items, $num)
  51. {
  52.     $cnt = 0;
  53.     foreach($items as $item)
  54.     {
  55.         if($item->folder_id > $num)
  56.         {
  57.             $cnt++;
  58.         }
  59.     }
  60.     return $cnt;
  61. }
  62.  
  63. foreach ($items as $item)
  64. {
  65.     if (folder_count($items, 1))
  66.     {
  67.         //do something to $item->folder_id=1/$item->item_id=1, item_id=2
  68.     }
  69.     else
  70.     {
  71.         //do something else to $item->folder_id=2/$item->item_id=3 and folder_id=3/item_id=4
  72.     }
  73. }