PHP数组常用键的总和值

时间:2013-11-29 04:58:45

标签: php arrays

我有以下数组

$data = array (
    "192.168.10.101" => array (
        "param1" => 80,
        "param2" => 3
    ),

    "192.168.10.99" => array (
        "param1" => 50,
        "param2" => 4
    )
);

我想将param1的总和192.168.10.101和[{1}} param1的公共密钥的值相加。

5 个答案:

答案 0 :(得分:1)

$result = array_shift($array);
foreach ($array as $val) {
    foreach ($val as $key => $val) {
        $result[$key] += $val;
    }
}

print_r($result)

Array ( 
    [param1] => 130 
    [param2] => 7 
) 

答案 1 :(得分:0)

$myArray = array(
    "192.168.10.101" => array (
        "param1" => 80,
        "param2" => 3
    ),

    "192.168.10.99" => array (
        "param1" => 50,
        "param2" => 4
    )
);
$sumArray = 0;
foreach ($myArray as $k=>$subArray) {
  if(isset($subArray['param1']))
    $sumArray +=$subArray['param1'];
}

print_r($sumArray);

答案 2 :(得分:0)

<?php
$data = array(
    "192.168.10.101" => array (
        "param1" => 80,
        "param2" => 3
    ),

    "192.168.10.99" => array (
        "param1" => 50,
        "param2" => 4
    )
);
$param_1=0;
$param_2=0;
foreach($data as $dat)
{
    $param_1+=$dat['param1'];
    $param_2+=$dat['param2'];

}

echo $param_1;
echo $param_2;

答案 3 :(得分:0)

$param_total = 0;
foreach($data as $key => $val){
    $param_total += $val['param1'];
}
echo $param_total;

答案 4 :(得分:0)

您可以尝试,(因为存在密钥)

  if(isset($data['192.168.10.101']["param1"]) && isset($data['192.168.10.99']["param1"]))
  {
     $data['192.168.10.101']["param1"] += $data['192.168.10.99']["param1"];
  }