PHP循环键。组匹配值,计算键值

时间:2016-01-26 14:09:41

标签: php html arrays

这是我的PHP数组:

Array (
  [0] => Array ( [heigth] => 6300 [type] => A [length] => 2370 )
  [1] => Array ( [heigth] => 1150 [type] => B [length] => 5510 )
  [2] => Array ( [heigth] => 1150 [type] => C [length] => 7150 )
  [3] => Array ( [heigth] => 1150 [type] => A [length] => 3540 )
);

现在我想计算每种类型的总面积。 您可以看到类型“A”存在2次。

所以我需要遍历我的数组,组类型并计算heigth * length。

我想我的问题是“类型”可以是任何东西。我不能硬编码。

让我们开始吧:

for($i = 0; $i < $rowCountArray; $i++){
  //Grab type
  $type = $array[$i]['type'];
  //Calc Area
  $area = $array[$i]['heigth'] * $array[$i]['length'];

  //Here i need something like an if statement. But also i need dynamic added vars?!
  //if(type is NEW) if(type exists) 

  $type1_Area += $area; //Seperated by types
  $type2_Area += $area; 
}

2 个答案:

答案 0 :(得分:2)

如何建立一系列总和?

mInitialValue As New List(Of T)
Private Property DataSource As BindingList(Of T)
    Get
        If DataGridViewSuppliers.DataSource Is Nothing Then
            DataGridViewSuppliers.DataSource = New BindingList(Of T)
        End If
        Return CType(DataGridViewSuppliers.DataSource, BindingList(Of T))
    End Get
    Set(value As BindingList(Of T))
        DataGridViewSuppliers.DataSource = value
    End Set
End Property

  DataSource = lElements
  mInitialValue = lSuppAccounts.ToList()

答案 1 :(得分:0)

未经测试,但这应该有用吗?

如果区域中没有区域,您只想将区域设置为0,然后根据需要设置每个类型的总区域。

$arr = array(
  array('height' => 6300, 'type' => 'A', 'length' => 2370),
  array('height' => 1150 , 'type' => 'A', 'length' => 5510 ),
  array('height' => 1150 , 'type' => 'A', 'length' => 7150),
  array('height' => 1150 , 'type' => 'A', 'length' => 3540 ),
);

$area = array();

foreach ($arr AS $item) {
  if (!isset($area[$item['type']])) $area[$item['type']] = 0;
  $area[$item['type']] += $item['type'] * $item['length'];
}