Php数组:为键'y'的相同值添加键'x'的值

时间:2017-12-17 02:37:06

标签: php arrays

如何为内部数组的键0 的类似值添加内部数组键2 的值

感谢您的帮助,我坚持这个问题。让我解释一下,我有这种阵列。

  array (size=6)
  0 => 
    array (size=4)
      0 => float 10002
      1 => string 'xxxyyyy' (length=7)
      2 => float 5.00
      3 => float 0
  1 => 
    array (size=4)
      0 => float 10002
      1 => string 'xxxyyyy' (length=7)
      2 => float 5.00
      3 => float 4.25
  2 => 
    array (size=4)
      0 => float 10002
      1 => string 'xxxyyyy' (length=7)
      2 => float 5.00
      3 => float 0
  3 => 
    array (size=4)
      0 => float 10010
      1 => string 'yyyyyyy' (length=7)
      2 => float 10.00
      3 => float 0
  4 => 
    array (size=4)
      0 => float 10010
      1 => string 'yyyyyyy' (length=7)
      2 => float 10.00
      3 => float 1.85
  5 => 
    array (size=4)
      0 => float 10010
      1 => string 'yyyyyyy' (length=7)
      2 => float 10.00
      3 => float 0

是否可以得到这个结果(如果key0值与内部数组相同,那么求和key2值)

sum_key_2 = 15, for key_0 = 10002
sum_key_2 = 30, for key_0 = 10010

我尝试了这个但没有获得所需的输出:

$bill = 0; $sp_no = array();
foreach($data as $innerKey => $innerArray) {
  $sp_no[] = $innerArray[0];
}

foreach($data as $k => $val) {
  if ($sp_no[$k] == $val[0]) {
    $bill += $val[2];
  }
}
echo $bill;

2 个答案:

答案 0 :(得分:1)

您可以先使用key_0作为密钥对其进行分组,然后在key_2组内添加每个对应的key_0

$result = [];                            // Initialize result array
foreach ($data as $value) {              // Loop thru data array
    if (!isset($result[$value[0]])) {    // Check if key_0 is on result array
        $result[$value[0]] = $value[2];  // Create new with value of key_2
    } else {
        $result[$value[0]] += $value[2]; // Increment with value of key_2
    }
}

// Printing result
foreach ($result as $key => $value) {
    echo 'sum_key_2 = ' . $value . ', for key_0 =' . $key . '<br>';
}

答案 1 :(得分:0)

你可以尝试这个解决方案

我假设您将尝试匹配数组[0]和数组[2]

$fullArray = [
    0 =>
        [
            0 => 10002,
            1 => 'xxxyyyy',
            2 => 5.00,
            3 => 0,
        ],
    1 =>
        [
            0 => 10002,
            1 => 'xxxyyyy',
            2 => 5.00,
            3 => 4.25,
        ],
    2 =>
        [
            0 => 10002,
            1 => 'xxxyyyy',
            2 => 5.00,
            3 => 0,
        ],
    3 =>
        [
            0 => 10010,
            1 => 'yyyyyyy',
            2 => 10.00,
            3 => 0,
        ],
    4 =>
        [
            0 => 10010,
            1 => 'yyyyyyy',
            2 => 10.00,
            3 => 1.85,
        ],
    5 =>
        [
            0 => 10010,
            1 => 'yyyyyyy',
            2 => 10.00,
            3 => 0,
        ]
];

for($i = 0; $i < count($fullArray); $i++) {
    if($fullArray[0][$i] != $fullArray[2][$i]) {
        // do your logic here
    } else {
        //do else logic here
    }
}