[英]php PDO MySQL Select results of one table based on array of results from another table
[英]Assigning an array key based on results from another table in PHP
我有一个标准表来存储表单输入,其中包含“ firstName,lastName,email”列。 实际上还有很多,但为简单起见,我将其保留为3。 这些字段需要发送到外部API,但是键实际上是整数...因此,“ firstName”实际上是作为“ 12345”发送到API的。
我还有第二张表,其中包含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++;
}
这可行,但显然不是最佳的,因为它运行多个查询。 有办法清理吗?
我想出了一个解决方案,可能会对某人有所帮助。 其他(更好)的解决方案也将不胜感激。
// 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个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.