亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

計算一個值在一個數組中出現的次數,該數組在另一個值下分組(年)

計算一個值在一個數組中出現的次數,該數組在另一個值下分組(年)

PHP
MMTTMM 2021-05-05 17:08:36
我有一個數組,里面有一些信息。有兩個重要的鍵datum和answer。我想查看密鑰answer每年對值進行fout分組的次數(datum包含年份,因此在此數組中有兩年2019和2020)我如何看待2019年和2020年fout發生多少次datum?因此,例如,我看到以下內容:2019 - 5 times fout2020 - 0 times fout我試圖在創建數組的循環中進行計數,但由于某種原因,它總是返回0。這是我之前嘗試過的(開始):while($getwpi = $getwpicon->fetch_assoc()){  $year = date('Y', strtotime($getwpi['datum']));  $getwpi['datum'] = $year; // update your field  $wpi[] = $getwpi; // add to the result array  $counted = count($wpi['datum']);}但$counted返回0。這是我目前的循環:while($getwpi = $getwpicon->fetch_assoc()){  $year = date('Y', strtotime($getwpi['datum']));  $getwpi['datum'] = $year; // update your field  $wpi[] = $getwpi; // add to the result array}
查看完整描述

3 回答

?
守候你守候我

TA貢獻1802條經驗 獲得超10個贊

您可以在循環內添加計數:


while($getwpi = $getwpicon->fetch_assoc()){

  $year = date('Y', strtotime($getwpi['datum']));

  $getwpi['datum'] = $year; // update your field


  if ($getwpi['answer'] == "fout") {

      $res[$year] = isset($res[$year]) ? $res[$year] + 1 : 1;

  }

  $wpi[] = $getwpi; // add to the result array

}

現在,$res將使用每年計數的數組。您可以在其上循環打印所需的內容。


查看完整回答
反對 回復 2021-05-28
?
互換的青春

TA貢獻1797條經驗 獲得超6個贊

您可以使用array_walk和array_key_exists來解決這個問題


$res=[];

array_walk($arr, function($v, $k) use (&$res){//$arr is the main array

  $res[$v['datum']] = (array_key_exists($v['datum'],$res) && !empty($v['answer'])) ? ($res[$v['datum']]+=1) : 1;

});

echo '<pre>';

print_r($res);

輸出示例:


Array

(

  [2019] => 4

)


查看完整回答
反對 回復 2021-05-28
  • 3 回答
  • 0 關注
  • 162 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號