简体   繁体   English

更好的查询解决方案

[英]Better solution to this query

$query = $this->db->query("SELECT field_name FROM table_name;");

        $getData= array();

        foreach ($query->result() as $row) {

            array_push($getData, $row->field_name);
        }

I use codeigniter, for every table that I need to manage if the data exist for update or make a new insert I use this code so i would like to see is there are more options for dont replicate the code every time. 我使用codeigniter,对于需要管理数据是否存在以进行更新或进行新插入的每个表,我都使用此代码,因此我希望看到是否还有更多选项可用于每次都不复制代码。 I'm just a student, sorry for mi english 我只是一个学生,对不起mi english

It is not clear why you are doing this, but I would call it "flattening" the array. 目前尚不清楚为什么要这样做,但我称其为“拉平”阵列。 If you find the need to do this often then creating a "worker" method might help. 如果您发现经常需要这样做,那么创建“工作者”方法可能会有所帮助。

For example, in a model, you might have two methods that both need "flat" results. 例如,在模型中,您可能有两种都需要“平坦”结果的方法。

public function get_something()
{
    $query = $this->db->query("SELECT field_name FROM table_name;");
    //call the "worker"
    return $this->make_flat($query);
}

public function get_something_else()
{
    $query = $this->db->query("SELECT field_name FROM table_name;");
    //call the "worker"
    return $this->make_flat($query);
}

Elsewhere in the model, there is this "worker" method used in the code above used. 在模型的其他地方,上面的代码中使用了这种“工人”方法。

// The "worker" method to flatten the results
protected function make_flat($query)
{
    $getData = []; //is same as $getData = array(); but with less typing
    foreach ($query->result() as $row)
    {
        $getData[] = $row->field_name;
    }
    return $getData;
}

The line $getData[] = $row->field_name; $getData[] = $row->field_name; does exactly the same thing as array_push($getData, $row->field_name); array_push($getData, $row->field_name);完全相同array_push($getData, $row->field_name); . But it is actually a bit faster. 但这实际上要快一些。 It is also less typing. 它的打字也更少。

http://php.net/manual/en/function.array-column.php should work great for this. http://php.net/manual/zh-CN/function.array-column.php应该对此非常有用

$query = $this->db->query("SELECT field_name FROM table_name;");

$array = array_column($query, 'field_name');

print_r($array);

your question seems to contradict your code. 您的问题似乎与您的代码相矛盾。 if you just want to see if a particular entry already exists you can do: 如果您只想查看特定条目是否已存在,可以执行以下操作:

$this->db->where('field_name', $var);
$exists = $this->db->count_all_results('table_name');
if ($exists > 0) {
    // update
    // there is an entry with $var for `field_name` in table `table_name`
} else {
    // insert
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM