我正在尝试执行一项功能,即搜索多维数组中的值并将结果中的值相加。数组如下
$arr = array (
'MY106782'=> array ('code'=>"MY106782",'totalSales'=>"5625.00",'SponsorID'=>"MY246913"),
'MY126192'=> array ('code'=>"MY126192",'totalSales'=>"5625.00",'SponsorID'=>"MY126637"),
'MY128276'=> array ('code'=>"MY128276",'totalSales'=>"3180.00",'SponsorID'=>"MY106782"),
'MY157278'=> array ('code'=>"MY157278",'totalSales'=>"5625.00",'SponsorID'=>"MY477500"),
'MY167585'=> array ('code'=>"MY167585",'totalSales'=>"5625.00",'SponsorID'=>"MY106782")
);
我试图搜索所有' MY106782'在" SponsorID"内数组,得到' totalSales'找到时的值,如果是多个记录,则添加值
非常感谢任何帮助。
答案 0 :(得分:0)
尝试这样的事情
$i = 0;
foreach ($arr as $key => $value) {
if ($value['SponsorID'] == 'MY106782') {
$i++;
}
}
输出 2
答案 1 :(得分:0)
由于您的数组是键值对数组,因此您必须确定要查找的键。检查一下:
$sponsor_id = "MY106782";
$total_sales = 0;
$arr = array (
'MY106782'=> array ('code'=>"MY106782",'totalSales'=>"5625.00",'SponsorID'=>"MY246913"),
'MY126192'=> array ('code'=>"MY126192",'totalSales'=>"5625.00",'SponsorID'=>"MY126637"),
'MY128276'=> array ('code'=>"MY128276",'totalSales'=>"3180.00",'SponsorID'=>"MY106782"),
'MY157278'=> array ('code'=>"MY157278",'totalSales'=>"5625.00",'SponsorID'=>"MY477500"),
'MY167585'=> array ('code'=>"MY167585",'totalSales'=>"5625.00",'SponsorID'=>"MY106782")
);
foreach($arr as $values) {
if($values["SponsorID"] == $sponsor_id) {
$total_sales += (float)$values["totalSales"];
}
}
echo $sponsor_id . " - " . $total_sales;
答案 2 :(得分:0)
如果密钥在数组中只存在一次,则可以使用以下脚本。
$arr = array (
'MY106782'=> array ('code'=>"MY106782",'totalSales'=>"5625.00",'SponsorID'=>"MY246913"),
'MY126192'=> array ('code'=>"MY126192",'totalSales'=>"5625.00",'SponsorID'=>"MY126637"),
'MY128276'=> array ('code'=>"MY128276",'totalSales'=>"3180.00",'SponsorID'=>"MY106782"),
'MY157278'=> array ('code'=>"MY157278",'totalSales'=>"5625.00",'SponsorID'=>"MY477500"),
'MY167585'=> array ('code'=>"MY167585",'totalSales'=>"5625.00",'SponsorID'=>"MY106782")
);
$key_to_check = 'MY157278';
if (array_key_exists($key_to_check, $arr)) {
echo $arr[$key_to_check]['totalSales'];
}else{
echo "key not found."
}