如何在PHP循环中基于同一个键组合数组值
我试图在foreach循环中创建一个数组,在这个数组中,特定医生的患者按药物计数,但我在数组中只得到一个数字,这是错误的,因为我正在生成一个带有响应的图表,我需要所有患者在一个数组中计数。此外,如果该医生没有该药物的数据,则需要为0 这是来自服务器的当前响应如何在PHP循环中基于同一个键组合数组值,php,arrays,Php,Arrays,我试图在foreach循环中创建一个数组,在这个数组中,特定医生的患者按药物计数,但我在数组中只得到一个数字,这是错误的,因为我正在生成一个带有响应的图表,我需要所有患者在一个数组中计数。此外,如果该医生没有该药物的数据,则需要为0 这是来自服务器的当前响应 array:5 0 => array:4 "patientsCount" => 2 "brand_name" => "Medicine 1" "month" => "April"
array:5
0 => array:4
"patientsCount" => 2
"brand_name" => "Medicine 1"
"month" => "April"
"physician_name" => "John Doe"
]
1 => array:4
"patientsCount" => 1
"brand_name" => "Medicine 2"
"month" => "April"
"physician_name" => "Jane Doe"
]
2 => array:4
"patientsCount" => 5
"brand_name" => "Medicine 3"
"month" => "July"
"physician_name" => "John Doe"
]
3 => array:4
"patientsCount" => 5
"brand_name" => "Medicine 2"
"month" => "July"
"physician_name" => "Jane Doe"
]
4 => array:4
"patientsCount" => 2
"brand_name" => "Medicine 4"
"month" => "June"
"physician_name" => "John Doe"
]
]
在我的foreach循环中,我正在这样做
$arr[ $item['physician_name'] ] = [ $item['patientsCount'] ];
这给了我这个
array:2
"John Doe" => array:1
0 => 2
]
"Jane Doe" => array:1
0 => 5
]
]
我的预期结果是这样的
0 => array:5
"label" => "John Doe"
"data" => array:5
0 => 3
1 => 0
2 => 8
3 => 7
4 => 4
]
"borderWidth" => 1
"backgroundColor" => "rgba(226,46,111,0.2)"
"borderColor" => "rgba(226,46,111,1)"
]
1 => array:5
"label" => "Jane Doe"
"data" => array:5
0 => 6
1 => 7
2 => 0
3 => 11
4 => 4
]
"borderWidth" => 1
"backgroundColor" => "rgba(226,46,111,0.2)"
"borderColor" => "rgba(226,46,111,1)"
]
]
如何获取所需的数组?在
$arr[ $item['physician_name'] ] = [ $item['patientsCount'] ];
您将使用包含$item['patientsCount']
的数组不断覆盖数组的同一元素。您想要的是添加到此数组中
$arr[ $item['physician_name'] ][] = $item['patientsCount'];
注意=
左侧的[]
,这意味着将值添加到此数组的末尾