2011-05-09 43 views
0

我有一个标准表来存储表单输入,列名为“firstName,lastName,email”。实际上还有更多,但为了简单起见,我将它保留为3。这些字段需要发送到外部API,但键实际上是整数...所以“firstName”实际上以“12345”的形式发送到API。根据PHP中另一个表的结果分配一个数组键值

我有第二个表具有API键和表单键。

我正在建立一个使用API​​密钥和表单值的数组。例如:$ data [12345] ='John'。实际上,如果有多个表单提交,它应该是$ data [0] [12345] ='John',$ data [1] [12345] ='Jane',依此类推。

这是我目前的解决方案:

//$return is an object containing all the form submissions 
$i = 0; 
     $data = array(); 
     foreach ($return as $ret) { 
      foreach ($ret as $k => $v) { 
        // function that runs a mySQL query "SELECT apikey FROM api WHERE formkey = '$k'" and returns the apikey 
        $apikey = getApiKey($k); 
        $data[$i][$apikey] = $v; 
      } 
      $i++; 
     } 

这工作,但显然不是最佳的,因为它运行多个查询。有没有办法清除它?

回答

0

以下是我想出的一种解决方案,可能有助于某人。其他(更好的)解决方案也将被赞赏。

// I'm using CodeIgniter, but this just puts the apikey into an array with the formkey as the array key 

$sql = "SELECT apikey,formkey FROM api"; 
$query = $this->db->query($sql); 
$return = array(); 
foreach ($query->result() as $row) { 
    $return[$row->formkey] = $row->apikey; 
} 

$i = 0; 
$data = array(); 
foreach ($return as $ret) { 
    foreach ($ret as $k => $v) { 
     $data[$i][$return[$k]] = $v; 
    } 
    $i++; 
} 

这砍下80我的数据库调用到2

相关问题