如何正确遍历数组?

时间:2018-09-20 04:14:18

标签: loops

我正在尝试实施一种解决方案,以找出页数最多的 MONTH 。有谁知道如何循环通过这个JSON数组,以便我也许可以提取每个月的$ total($ total1,$ total2,$ total3,... $ total12),然后将它们添加到数组中,然后找到最大数量(意味着页面数最多的月份)?

这是到目前为止我一个月以来一直在尝试的方式:

   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;
                      }
               }
          }
    }

1 个答案:

答案 0 :(得分:2)

您可以像这样计算月份的页面数:

$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);

结果将如下所示

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

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

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

)

您可以找到这样的最大物品:

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

结果将是这样

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