代码之家  ›  专栏  ›  技术社区  ›  Devmix

如何正确循环数组?

  •  1
  • Devmix  · 技术社区  · 6 年前

    我正在尝试实施一个解决方案来找出 页数最多的。有没有人知道如何循环使用这个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 回复  |  直到 6 年前
        1
  •  2
  •   Flames    6 年前

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

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