如何根据它的父级计算foreach循环中的项目数?

时间:2018-02-02 04:05:30

标签: php foreach

我有一个简单的循环来显示列表。但我不知道如何计算它的父项。这是我目前的尝试:

$no = 0;
$ct = 0;
$type = "";
foreach($item as $row_item){
   $no = $no + 1;

   if($type != $row_item['type']){
      $ct  = $ct + 1;
   }

   echo $no." ".$row_item['type']." ".$row_item['item'];


  $type = $row_item['type'];

}

我想要的输出:

1   TYPE_A   3   A1
2   TYPE_A   3   A2
3   TYPE_A   3   A3
4   TYPE_B   2   B1
5   TYPE_B   2   B2

2 个答案:

答案 0 :(得分:0)

为了计算每种类型的总数,您需要迭代整个集合两次。一次计算总数,一次显示每行的结果。下面的代码实际上做了3个循环,array_filter方法迭代整个数组,但我喜欢干净的代码。 :)

http://sandbox.onlinephpfunctions.com/code/962f418715d1518c818732f6e59ba4f28d5a19f3

<?php
$items = array( 
  array( 'name' => 'A1', 'type' => 'TYPE_A' ),
  array( 'name' => 'A2', 'type' => 'TYPE_A' ),
  array( 'name' => 'A3', 'type' => 'TYPE_A' ),
  array( 'name' => 'B1', 'type' => 'TYPE_B' ),
  array( 'name' => 'B2', 'type' => 'TYPE_B' )
);

function is_TYPE_A( $item ) {
  return $item['type'] == 'TYPE_A';
}
function is_TYPE_B( $item ) {
  return $item['type'] == 'TYPE_B';
}

$TYPE_A_COUNT = count( array_filter( $items, 'is_TYPE_A' ) );
$TYPE_B_COUNT = count( array_filter( $items, 'is_TYPE_B' ) );

function getTypeTotalByItem( $item ) {
  global $TYPE_A_COUNT, $TYPE_B_COUNT;
  if ( $item['type'] == 'TYPE_A' ) {
    return $TYPE_A_COUNT;
  }
  if ( $item['type'] == 'TYPE_B' ) {
    return $TYPE_B_COUNT;
  }
}

for ( $i = 0; $i < count( $items ); $i++ ) {
  echo ( $i + 1 )." ".$items[$i]['type']." ".getTypeTotalByItem($items[$i])." ".$items[$i]['name']."\n";
}

答案 1 :(得分:0)

如果您愿意,可以使用array_map()和几个foreach()循环。它应该很快解释:

# Create a storage array
$counter    =   [];
# Sort the main array into type
array_map(function($v) use (&$counter){
    # Store the subs under the type
    $counter[$v['type']][]  =   $v['item'];
},$items);
# Start counter
$i = 1;
# Loop through each type
foreach($counter as $title => $row){
    # Count how many are under this type
    $count  =   count($row);
    # Loop the rows in the types arrays
    foreach($row as $item) {
        # Write increment, type, total count, item
        echo $i." ".$title." ".$count." ".$item.'<br />';
        $i++;
    }
}