ActiveRecord where_in() with array [closed]

2020-04-08 07:20发布

问题:

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 6 years ago.

I have tried a few different approaches to this problem with no solutions so far. I am receiving this error message:

Unknown column 'Array' in 'where clause'

SELECT * FROM (Articles) WHERE id IN (Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array, Array)

Here is my model code:

function getStarNews($user_id) {
    $this->db->select('id');
    $this->db->where('user_id', $user_id);
    $query = $this->db->get('table1');

    foreach ($query->result_array() as $id)
    {
        //echo $id['id']."<br>"; //displays all of the correct ids I am trying to pass to the where_in()
    }
    $id = $query->result_array();

    $this->db->where_in('id', $id); //pass array of 'id' from above query
    $data = $this->db->get('Articles');

    return $data->result_array();
}

If I alter the id array to contain only 1 value then the where_in() clause works fine and outputs the row of data matching the single 'id'.

I've looked all over stack and google for help in using where_in() and I think I have everything correct or have tried a few different methods for passing an array correctly.

Thanks for the help.

EDIT: In the end I will be outputting this data with my controller using:

$this->output->set_output(json_encode($data));

For testing purposes I was just skipping the JSON and trying to output the data with PHP from the model directly.

回答1:

The array you try to pass is a multi dimensional array. Instead try this:

$ids = array();
foreach ($query->result_array() as $id)
    {
        $ids[] = $id['id'];
    }

$this->db->where_in('id', $ids);

You can not flatten the query->result_array() without iteration. But if you need to handle this kind of queries a lot in your application, and if you have >= PHP 5.3 installed, you could put the following function in a Codeigniter helper file (or somewhere else suitable) to help you flattening arrays:

function flatten(array $array) {
    $return = array();
    array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
    return $return;
}

And in your case use it like this:

    $ids = flatten($query->result_array());
    $this->db->where_in('id', $ids);