繁体   English   中英

如何有效搜索数组以填写表单字段?

[英]How do I efficiently search an array to fill in form fields?

我正在寻找一种有效的方法将所需的数据从一个名为$ submission_info的数组中提取出来,这样我可以轻松地自动填充表单字段。 阵列大小约为120。

我想找到字段名称并提取内容。 在这种情况下,字段名称为loanOfficer ,内容为John Doe

Output of Print_r($submission_info[1]):

Array ( 
     [field_id] => 2399 
     [form_id] => 4 
     [field_name] => loanOfficer 
     [field_test_value] => ABCDEFGHIJKLMNOPQRSTUVWXYZ 
     [field_size] => medium 
     [field_type] => other 
     [data_type] => string 
     [field_title] => LoanOfficer 
     [col_name] => loanOfficer 
     [list_order] => 2 
     [admin_display] => yes 
     [is_sortable] => yes 
     [include_on_redirect] => yes 
     [option_orientation] => vertical 
     [file_upload_dir] => 
     [file_upload_url] => 
     [file_upload_max_size] => 1000000 
     [file_upload_types] => 
     [content] => John Doe 
     ) 

我想找到字段名称并提取内容。 在这种情况下,字段名称为loanOfficer ,内容为John Doe

您最好是遍历每个条目并从中创建一个新的关联数组。

foreach($submission_info as $elem) {
    $newarray[$elem["field_name"]] = $elem["content"];
}

然后,您可以通过从$ newarray [ <您要填写的字段> ]中获取值来查找表单字段。 否则,您将不得不每次都在$ submission_info中搜索正确的字段。

不知道这是否是最佳解决方案:

foreach($submission_info as $info){
  if($info['field_name'] == 'loanOfficer'){ //check the field name
    $content = $info['content']; //store the desired value
    continue; //this will stop the loop after the desired item is found
  }
}

下次:如果您将问题概括化,以使它们涵盖您和其他人可能不理解的总体主题,对您和其他人会更有用。 似乎您可以使用数组复习课程...

我假设php有一个关联数组(通常称为字典或哈希表)。 最有效的例程是对数组运行一次​​,然后将字段放入以字段名称为关键字的字典中。

然后,当您要查找特定字段(O(n))操作时,不必搜索原始数组。 您只是使用字典通过O(1)(或常量)操作中的字段名称来检索它。 当然,通过数组填充字典的第一遍将是O(n),但这是一次性的费用,而不是每次查找都要付出相同的代价。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM