Devmix
Devmix

Reputation: 1868

How to loop properly through an array?

I'm trying to implement a solution to find out the MONTH that has the most number of pages. Does anyone know how to loop though this JSON array so that I can maybe extract the $total for each month ($total1, $total2, $total3, ...$total12) and then maybe add them to an array and then find the max number(meaning the Month that has most pages)?

This is the way I'm trying so far for a single month:

   foreach($my_array as $value){
                  foreach ($value->all_books as $all_book) {
                      foreach ($all_book->number_of_pages as $num_page) {
                        if ($num_page->number_of_books && $num_page->pages) {
                       $total += $num_page->number_of_books * $num_page->pages;
                      }
               }
          }
    }

Upvotes: 1

Views: 62

Answers (1)

Midhun
Midhun

Reputation: 1167

You can count page count of month like this :

$monthWisePageCount = array();
foreach($my_array as $value){
    $month = date('M', strtotime($value->datetime_status));
          if(!in_array($month, array_keys($monthWisePageCount))){
               $monthWisePageCount[$month]['count'] =  0;
               $monthWisePageCount[$month]['month'] =  date('F', strtotime($value->datetime_status));
          }
            foreach ($value->all_books as $all_book) {
                      foreach ($all_book->number_of_pages as $num_page) {
                        if ($num_page->number_of_books && $num_page->pages) {
                             $monthWisePageCount[$month]['count'] += $num_page->number_of_books * $num_page->pages;
                      }
               }
          }

    }
print_r($monthWisePageCount);

The result will look like this

  Array
(
    [Mar] => Array
        (
            [count] => 900
            [month] => March
        )

    [Dec] => Array
        (
            [count] => 558
            [month] => December
        )

    [Oct] => Array
        (
            [count] => 280
            [month] => October
        )

)

You can find the largest item like this :

    $largestKey = '';
    $largestCount = 0 ; 
    foreach($monthWisePageCount as $key => $item){
           if($item['count'] > $largestCount ) {
               $largestCount = $item['count'];
                $largestKey =   $key;
           }
    }
 $monthWithLargestPageCount = $monthWisePageCount[$largestKey];
 print_r($monthWithLargestPageCount);

The result will be like this

Array ( [count] => 900 [month] => March )

Upvotes: 2

Related Questions