php 数组到字符串转换错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11510398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:42:23  来源:igfitidea点击:

Array to string conversion error

phparraysstringcodeigniterimplode

提问by Dylan Buth

I have a query that's pulling a list of IDs. Those IDs are in an array and I need to search another table with those IDs. I tried using implode to make those IDs a string that I could use in a where clause but I keep getting this error.

我有一个查询正在提取 ID 列表。这些 ID 在一个数组中,我需要用这些 ID 搜索另一个表。我尝试使用 implode 使这些 ID 成为我可以在 where 子句中使用的字符串,但我不断收到此错误。

My current code is:

我目前的代码是:

 $query = $this->db->query('
        SELECT *
        FROM system_scoperights
        WHERE user = '. $this->session->userdata('username') .'
    ');

    foreach ($query->result() as $row) {
        $scope = $row->site;
        $data[] = $scope;
    } 
    $dataScope[] = $data;

    $idList = implode(',', $dataScope);   <---- Error Line

    $where = 'WHERE scope_scopes.sc_ID IN '. $idList .'';

I've tried different things I found on forums like:

我尝试了在论坛上发现的不同内容,例如:

 $idList = implode(',', array_values($dataScope));

and

 $idList = implode(',', join($dataScope));

but none of those work. (I've never even heard of the join function)

但这些都不起作用。(我什至从未听说过 join 功能)

Thanks in advance for the help.

在此先感谢您的帮助。

回答by Jay

$dataScope[] = $data;

but

$data[] = $scope;

therefore $dataScopehas an array inside it's array. implodeonly work on one level, so that why you're getting this error.

因此$dataScope它的数组中有一个数组。implode仅在一个级别上工作,因此您会收到此错误。

You should note that this is actually possible in SQL:

您应该注意到这在 SQL 中实际上是可能的:

 SELECT * FROM some_table WHERE id IN (SELECT site FROM another_table WHERE ... )

which would eliminate the entire need for this code.

这将消除对这段代码的全部需求。

That is:

那是:

$where = 'WHERE scope_scopes.sc_ID IN (SELECT site
                                       FROM system_scoperights
                                       WHERE user = '. $this->session->userdata('username') . ')';

回答by lerxstrulz

I partially agree with Jay's answer...just remove the line:

我部分同意 Jay 的回答......只需删除该行:

$dataScope[] = $data

and use the $datavariable directly since it's already an array:

$data直接使用该变量,因为它已经是一个数组:

$idList = implode(',', $data);

However you also should use ( and ) in your where clause:

但是,您也应该在 where 子句中使用 (和):

$where = 'WHERE scope_scopes.sc_ID IN (' . $idList . ')';

Using sub-queries in your where clauses, although they do have their place at times, can cost a lot of overhead, especially using 'SELECT *'. Never ask for more than you need from your db tables :)

在您的 where 子句中使用子查询,虽然它们有时确实有其一席之地,但会花费大量开销,尤其是使用“SELECT *”。永远不要从你的数据库表中要求超过你需要的 :)