开发者

Assigning an array key based on results from another table in PHP

开发者 https://www.devze.com 2023-03-03 19:20 出处:网络
I\'ve got a standard table to store form input, with columns \"firstName,lastName,email\". There are actually quite a few more, but I\'ll leave it at 3 for simplicity\'s sake.Those fields need to be s

I've got a standard table to store form input, with columns "firstName,lastName,email". There are actually quite a few more, but I'll leave it at 3 for simplicity's sake. Those fields need to be send to an external API, but the keys are actually integers... so "firstName" is actually sent as "12345" to the API.

I've got a second table that has the API keys and the form keys开发者_开发问答.

I'm looking to build an array that uses the API keys and the form value. For example: $data[12345] = 'John'. And actually, if there are multiple forms to submit, it should be $data[0][12345] = 'John', $data[1][12345] = 'Jane', and so on.

Here's my current solution:

//$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++;
        }

This works, but is obviously not optimal since it runs multiple queries. Is there a way to clean this up?


Here's one solution I figured out, that may help someone. Other (better) solutions would also be appreciated.

// 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++;
}

This cut down my database calls from 80 down to 2.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号