Paste Search Dynamic
Recent pastes
Sum of animals
  1. <?php
  2.  $array=array(array(1,'cat'),array(3,'mice'),[2,'horses']);
  3. //$array=array(array(1,'cat'),array(3,'mice'), array(3,'sheep'),[2,'horses']);
  4. //$array=array(array(1,'cat'),array(3,'mice'), array(6,'sheep'),[2,'horses']);
  5. print_r($array);
  6. //Sort array in ascending order before processing
  7. asort($array);
  8. //Count the number of animals into an array
  9. $countanimals = array_count_values(array_column($array, 1));
  10. print_r($countanimals);
  11. $sumofanimals = 0;
  12.  
  13. //Sum all the animals in $countanimals
  14. foreach ($countanimals as $k=>$value) {
  15. $sumofanimals+=$value;
  16. } ?>
  17. <table> <thead> <tr> <th>Animal</th> <th>Count</th> </tr> </thead>
  18. <tbody>
  19. <?php // Output table rows for the array count by key and value
  20.  
  21. foreach ($countanimals as $key => $value) {
  22.         echo '<tr><td>'.$key.'</td><td>'.$value.'</td></tr>';
  23. };
  24. ?>
  25.         </tbody>
  26.         <tfoot> <tr> <td>Sum of animals</td> <td><?php echo $sumofanimals;?></td> </tr> </tfoot>
  27. </table>
Parsed in 0.013 seconds