如何正确遍历数组?

程序

我正在尝试实施一种解决方案,以找出页数最多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;
                      }
               }
          }
    }
烈焰

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章