0

我有多个具有相似键/对集的数组。我想使用 a 循环遍历它们,foreach并且每页元素打印 2 个。

套:

 <div class="page_cargovolumes cy_detail">
  @foreach ($cargovolumes_cy as $cargos_cy)
   {!! $cargos_cy !!}
  @endforeach
</div>
<div class="page_cargovolumes ly">
 @foreach ($cargovolumes_ly as $cargos_ly)
  {!! $cargos_ly !!}
 @endforeach
</div>

如何将两者的循环输出用于包含两者的 1 个元素?

期望的结果:

<div class="page_cargovolumes ly">
  {!! $cargos_cy !!}
  <br>
  {!! $cargos_ly !!}
</div>

前任。db数据如下:

public function cargovolumes_cy() {
    global $wpdb;

    $cargodb = new $wpdb('root', 'expw', 'exdb', 'localhost');
    $currentmonthtxt = date('Y');
    $currentyear = date('Y');
    $cargovolume_cy = array();

    foreach($cargodb->get_results(
        "
        SELECT    *, SUM(tonneCount)
        FROM      volumes
        WHERE year = $currentyear
        GROUP BY terminal, year, month
        "
    )  as $key => $row) {
        $tonnages = $row->tonneCount;
        $terminal = $row->terminal;
        $year = $row->year;
        $month = $row->month;
        $cargovolume_cy[] = 
        '<div class="cargovolumes_cy"><h4>'.$terminal.' </h4>'. 
        '<span class="cv-year">Year: '.$year.' </span>'. 
        '<span class="cv-month"> Month: '.$month.' </span>'. 
        '<span class="cv-tonnage"> Tonnage: '.$tonnages.' </span></div>';
    };

    return $cargovolume_cy;

}

public function cargovolumes_ly() {
    global $wpdb;

    $cargodb = new $wpdb('root', 'expw', 'exdb', 'localhost');
    $currentmonthtxt = date('Y');
    $currentyear = date('Y');
    $cargovolume_ly = array();

    foreach($cargodb->get_results(
        "
        SELECT    *, SUM(tonneCount)
        FROM      volumes
        WHERE year = $currentyear -1
        GROUP BY terminal, year, month
        "
    )  as $key => $row) {
        $tonnages = $row->tonneCount;
        $terminal = $row->terminal;
        $year = $row->year;
        $month = $row->month;
        $cargovolume_ly[] = 
        '<div class="cargovolumes_ly">'. 
        '<span class="cv-year">Year: '.$year.' </span>'. 
        '<span class="cv-month"> Month: '.$month.' </span>'. 
        '<span class="cv-tonnage"> Tonnage: '.$tonnages.' </span></div>';
    };

    return $cargovolume_ly;

}
4

1 回答 1

2

foreach一次只操作一个数组,有两种方法可以获得您想要的结果。

出路1

<div class="page_cargovolumes ly">
@foreach (array_combine($cargovolumes_cy, $cargovolumes_ly) as $cargos_cy => $cargos_ly) 
   {!! $cargos_cy !!}
      <br>
   {!! $cargos_ly !!}
@endforeach
</div>

出路2

<div class="page_cargovolumes ly">
@foreach($cargovolumes_cy as $nIndex => $cargos_cy)
   {!! $cargos_cy !!}
      <br>
   {!! $cargovolumes_ly[$nIndex] !!}
@endforeach
</div>
于 2019-08-26T07:45:01.067 回答