如何在基于相同键的PHP循环中组合数组值

时间:2018-07-14 10:42:30

标签: php arrays

我正在尝试在foreach循环中创建一个数组,在该数组中患者将由特定医师的药物进行计数,但是我在数组中仅得到一个错误的数字,因为我正在生成带有响应的图表,并且我需要所有患者都排成一列。另外,如果没有该医生的该药物数据,则该数据必须为0。

这是服务器的当前响应。

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)"
      ]
    ]

如何获得预期的阵列?

1 个答案:

答案 0 :(得分:1)

在...

$arr[ $item['physician_name'] ] = [ $item['patientsCount'] ];

您将不断用包含$item['patientsCount']的数组覆盖数组的相同元素。您想要添加到该数组中...

 $arr[ $item['physician_name'] ][] = $item['patientsCount'];

请注意[]左侧的=,这意味着将值添加到此数组的末尾。