所以我有一个包含我需要在另一个表上加入的信息的数组,对于我需要将它加入到form_lookup表中的每个键,我需要用从我的数据库中检索到的数据替换数组的键。我的问题是什么是最快和最好的方法呢?我已经有了form_information数组
$form_titles =array();
foreach (form_information[0] as $key => $value) {
$this->db->select('NAME');
$this->db->from('form_lookup');
$this->db->where('CODE', $key );
$query = $this->db->get();
}
$form_names = $query->result_array();
$form_titles[] = $campus_forms;
现在我需要使用 form_titles 数组中的键替换 form_information 中的键。
$final_array = array_replace($form_information, $replacements);
[0] => Array
(
[FIELD_1] => information
[FIELD_2] => information
[FIELD_3] => information
[FIELD_4] => information
[FIELD_5] => information
...
)
CODE_ID | NAME
--------------
FIELD_1 | Name
--------------
FIELD_2 | ID
-------------
FIELD_3 | Contact
--------------
FIELD_4 | Lookup
-------------
FIELD_5 | Campus
[0] => Array
(
[Name] => information
[ID] => information
[Contact] => information
[Lookup] => information
[Campus] => information
...
)
答案 0 :(得分:1)
如果两个数组都包含相同的CODE_ID
且它们的顺序相同,那么PHP array_combine()
可能会有用。
数组array_combine(数组$ keys,数组$ values)
使用keys数组中的值作为键,将values数组中的值作为相应的值,创建一个数组。
这样的事情:
$new_array = array_combine($lookup,$initial_array);
答案 1 :(得分:1)
我会使用 foreach()和 array_combine()。
// Source data simulation..
$one_item = array(
"FIELD_1" => "information1",
"FIELD_2" => "information2",
"FIELD_3" => "information3",
"FIELD_4" => "information4",
"FIELD_5" => "information5"
);
$form_information[] = $one_item;
$form_information[] = $one_item;
$form_information[] = $one_item;
$form_information[] = $one_item;
$form_information[] = $one_item;
$keys = array(
"FIELD_1" => "name",
"FIELD_2" => "id",
"FIELD_3" => "contact",
"FIELD_4" => "lookup",
"FIELD_5" => "campus"
);
// The important part.
foreach ($form_information as $array){
$result[] = array_combine($keys, $array);
}
echo nl2br(print_r ($result, true));
..打印出来:
Array
(
[0] => Array
(
[name] => information1
[id] => information2
[contact] => information3
[lookup] => information4
[campus] => information5
)
[1] => Array
(
[name] => information1
[id] => information2
[contact] => information3
[lookup] => information4
[campus] => information5
)
......等等。
答案 2 :(得分:1)
array_combine(array_values($form_lookup), array_values($form_information));
答案 3 :(得分:1)
试试这个。
foreach($form_titles as $i => $v){
foreach($form_information as $q){
$form_information[$i] = $q;
}
}