如果键匹配,则从关联数组添加值

时间:2016-08-18 22:29:13

标签: php arrays sum

我正在尝试在键匹配时从关联数组中添加值。最终目标是能够实现这样的输出:

Total Ups: 219
Aug. 1 Ups: 105
Aug. 2 Ups: 52
Aug. 3 Ups: 62

我有以下工作一次性数组值:

foreach($array as $key => $value){
  foreach ($value['report']['daily']['ups'] as $rec){
    $upsArr[] = $rec;
  }
}

echo array_sum($upsArr);

然而,当我尝试计算单个日期的总和时,比如说8月1日,我似乎无法走到第二级别的键,但取得了任何成功。我有以下内容,看看能否达到所需水平:

foreach($array as $key => $subArr){
  foreach($subArr as $id => $value['report']['daily']['ups'][1]){
    print_r($value);
  }
}

这是我正在使用的数组:

$array = array(
  array(
    store  => 'South',
    report => array(
      daily  => array(
        ups => array('Aug. 1' => '19', 'Aug. 2' => '11', 'Aug. 3' => '13'),
        sold => array('Aug. 1' => '11', 'Aug. 2' => '5', 'Aug. 3' => '5')
    )),
  ),
  array(
    store  => 'East',
    report => array(
      daily  => array(
        ups => array('Aug. 1' => '38', 'Aug. 2' => '22', 'Aug. 3' => '23'),
        sold => array('Aug. 1' => '16', 'Aug. 2' => '8', 'Aug. 3' => '8')
    )),
  ),
  array(
    store  => 'West',
    report => array(
      daily  => array(
        ups => array('Aug. 1' => '48', 'Aug. 2' => '19', 'Aug. 3' => '26'),
        sold => array('Aug. 1' => '28', 'Aug. 2' => '4', 'Aug. 3' => '11')
    )),
  )
)

提前致谢。

1 个答案:

答案 0 :(得分:1)

查看

 var userInputString = "";
    while (true){

    var char = Console.Read();
    // append to userInputString
    // search your directory and suggest the path using a combination of SetCursorPosition and Console.Write and bring the cursor back to user's current typing position. Hint: store Console.CursorLeft in another variable before you use SetCursorPosition so that you can set the cursor position back. 
    // If user presses <TAB> to accept the suggestion or of the file path that user keyed in exists "break" the loop.
    // So the loop never exits until the user either keys in correct path or accepts the suggestion
    }