-2

所以我有一个数组,其中包含我需要加入另一个表的信息,对于每个键,我需要将它加入到 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);

form_information##(初始数组)

[0] => Array
            (
                [FIELD_1] => information
                [FIELD_2] => information
                [FIELD_3] => information
                [FIELD_4] => information
                [FIELD_5] => information
                ...
            ) 

表form_lookup

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
                    ...
                ) 
4

4 回答 4

1

如果两个数组都包含相同CODE_ID的 s 并且它们的顺序相同,那么 PHParray_combine()可能会很有用。

数组 array_combine ( 数组 $keys , 数组 $values )

通过将 keys 数组中的值用作键并将 values 数组中的值用作相应值来创建一个数组。

http://php.net/manual/en/function.array-combine.php

像这样的东西:

$new_array = array_combine($lookup,$initial_array);

这是一个工作示例

于 2013-09-06T00:18:55.433 回答
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
)

... ETC。

于 2013-09-06T00:21:10.880 回答
1
array_combine(array_values($form_lookup), array_values($form_information));
于 2013-09-06T00:25:10.813 回答
1

试试这个。

foreach($form_titles as $i => $v){
  foreach($form_information as $q){
    $form_information[$i] = $q;
  }
}
于 2013-09-06T00:28:47.487 回答