PHP:在多维数组中查找字符串或返回空数组键?

时间:2015-04-12 15:23:14

标签: php mysql arrays

我有一个多维数组$rows,它返回如下结果;我已经基于array_keys创建了查询。现在我遇到的问题是,如果没有空床并且我的所有查询都是折腾的话,$ rows可能会也可能不会返回一些行。

我尝试使用in_array函数,但看起来这样做不适用于多维数组。

array (size=6)
      0 => 
        array (size=2)
          'room_category' => string 'MALE GENERAL WARD' (length=17)
          'vacant_beds' => string 'MG-5' (length=4)
      1 => 
        array (size=2)
          'room_category' => string 'FEMALE GENERAL WARD' (length=19)
          'vacant_beds' => string 'FG-2,FG-3,FG-4' (length=14)
      2 => 
        array (size=2)
          'room_category' => string 'MOTHER CHILD WARD' (length=17)
          'vacant_beds' => string 'MC-1,MC-3,MC-4' (length=14)
      3 => 
        array (size=2)
          'room_category' => string 'NICU' (length=4)
          'vacant_beds' => string 'NICU-8,NICU-4,NICU-5,NICU-6,NICU-1,NICU-7,NICU-2' (length=48)
      4 => 
        array (size=2)
          'room_category' => string 'CLASSIC' (length=7)
          'vacant_beds' => string 'CL-9,CL-4,CL-5,CL-7,CL-8' (length=24)
      5 => 
        array (size=2)
          'room_category' => string 'DELUXE' (length=6)
          'vacant_beds' => string 'DLX-6,DLX-3,DLX-4,DLX-5' (length=23)

我应该采取什么方法,或确保即使特定病房不空置也会返回一行。

$ rows的代码是这样的:

select `rct`.`room_category` AS `room_category`,
    group_concat(`rn`.`room_name` separator ',') AS `vacant_beds` 
    from ((`room_name` `rn` join `room_category` 
    `rct` on((`rn`.`room_category` = `rct`.`id`))) 
    left join `patient_detail` `pd` on(((`rn`.`id` = `pd`.`bed_type`) 
    and (isnull(`pd`.`discharge_date`) or (now() between `pd`.`admission_date` and `pd`.`discharge_date`))))) 
    where isnull(`pd`.`id`) group by `rn`.`room_category`

1 个答案:

答案 0 :(得分:1)

您对空床查询的加入会遗漏空值。我建议您使用子查询生成room_category值的完整列表。

            select distinct room_category
              from room_category

然后我建议您将子查询LEFT JOIN到查询的其余部分,并使用其值进行分组。最终会看起来像这样:

select a.room_category, 
       group_concat(b.room_name ORDER BY b.room_name) vacancies
  from (select distinct id, room_category from room_category) a
  left join 
       (select rct.room_category AS room_category,
               rn.room_name 
          from room_category rct  
          left join room_name rn on rn.room_category = rct.id
          left join patient_detail pd on rn.id = pd.bed_type
                 and (isnull(pd.discharge_date) or now() 
                      between pd.admission_date and pd.discharge_date)
         where isnull(pd.id) 
         order by rct.room_category, rn.room_name
    ) b on a.room_category=b.room_category
group by a.room_category
order by a.room_category