搜索php关联数组(哈希映射)作为mysql

example

public $inputs=array(
    array(  'sysname'=>'pt_name','dbname' => 'users.name','label' => 'user (name/ID)','value' => '',
            'type' => 'text','rules' => 'required','attr'=>'class="autocomplete"'),

    array(  'sysname'=>'pt_dob','dbname' => 'users.dob','label' => 'Patient Dob','value' => '',
            'type' => 'text','rules' => 'required','attr'=>'class="dob ac" Disabled'),

    array(  'sysname'=>'pt_gender','dbname' => 'users.gender','label' => 'gender','value' => 'male,female',
            'type' => 'dropdown','rules' => 'required','attr'=>'class="ac" Disabled'),

    array(  'sysname'=>'visit_date','dbname' => 'visits.date','label' => 'Date','value' => '',
            'type' => 'text','rules' => 'required','attr'=>'class="datepicker"'),

    array(  'sysname'=>'visit_time','dbname' => 'visits.time_booked','label' => 'Time','value' => '',
            'type' => 'text','rules' => 'required','attr'=>'class="timepicker"'),

    array(  'sysname'=>'visit_type','dbname' => 'visits.type','label' => 'Visit type','value' => 'visit,schedule',
            'type' => 'dropdown','rules' => 'required','attr'=>'')
    );

how can i search this array for only arrays that have pt_ in its sysname for example ?

the idea is i have many types of rows all in same table, so instead of running a mysql query to fetch each type separatly example:

$pt=db->query("select * from table where sysname like 'pt_%'")->result();
$visit=db->query("select * from table where sysname like 'visit_%'")->result();

i want to fetch all at one and split them in php to decrease db load.

so how can i do this ? and is it worth it or better of keep my querys separate.

array_filter and a PHP-style closure* would be a pretty simple solution to this:

function buildFilter($key, $needle) {
    return function($array) use($key, $needle) {
        return (strpos($array[$key], $needle) !== FALSE);
    };
}
$matches = array_filter($inputs, buildFilter('sysname', 'pt_'));
var_dump($matches);
  • NB: What PHP calls a "closure" is quite a bit different from what most other languages use for the same term, so please make sure to read the PHP documentation.

Doing a couple of queries is fine, your DB can handle that easily. If you're doing dozens of queries for dozens of types (each with only a few rows), it might be worth investigation moving that logic to PHP.

What I would recommend is to put the systype in a separate column with an index on it. That will speed of your query a lot and take load of your DB. Even better is you can make that column an ENUM.

public $inputs=array(
    array(  'systype'=>'pt', 'sysname'=>'pt_name','dbname' => 'users.name','label' => 'user (name/ID)','value' => '',
            'type' => 'text','rules' => 'required','attr'=>'class="autocomplete"'),
    ...

$pt=db->query("select * from table where systype = 'pt'")->result();
$visit=db->query("select * from table where systype = 'visit'")->result();