【问题标题】:Passing array to like active record in codeigniter将数组传递给codeigniter中的活动记录
【发布时间】:2014-02-24 01:10:12
【问题描述】:

我想将数组传递给 codeignter 中活动记录的 like 子句,因为我写了以下内容:

$array_string = smart,intelligent,awesome;

$array_like = explode(',',$array_string);

在模型中:

$this->db->like('topic',array($array_like));

但我得到了

Severity: Notice
Message: Array to string conversion

任何帮助或建议都会有很大帮助。

在此处查看更新的问题: join not giving required result when using or_like codeigniter

【问题讨论】:

  • $array_like 已经是一个数组,因为explode(),也许将您的$this->db->like('topic',array($array_like)); 更改为$this->db->like('topic',$array_like);可能是一个好的开始。
  • @dqlopez 我已经尝试过,但再次数组以 strign 转换通知即将到来

标签: php arrays codeigniter activerecord


【解决方案1】:

您不能只将数组传递给like() 函数,它必须是字符串。您需要为字符串中的每个关键字应用like 子句。

您需要使用or_like 将记录与其中一个关键字匹配,但是,因为如果您每次只使用like(),则由于查询类似于@987654326,因此需要匹配所有关键字@ 等,这不是你需要的。

$array_string = "smart,intelligent,awesome";
$array_like = explode(',', $array_string);
foreach($array_like as $key => $value) {
    if($key == 0) {
        $this->db->like('topic', $value);
    } else {
        $this->db->or_like('topic', $value);
    }
}

尝试这种方式来避免where 语句的其余部分被忽略的问题。

$array_string = "smart,intelligent,awesome";
$array_like = explode(',', $array_string);

$like_statements = array();

foreach($array_like as $value) {
    $like_statements[] = "topic LIKE '%" . $value . "%'";
}

$like_string = "(" . implode(' OR ', $like_statements) . ")";

$like_string 的值将是 (topic LIKE '%smart%' OR topic LIKE '%intelligent%' OR topic LIKE '%awesome%')

然后您可以通过以下方式将$like_string 与 ActiveRecord 一起使用:

$this->db->where($like_string, FALSE);

【讨论】:

  • 非常感谢先生,我收到数据库错误:::
  • 在这里查看完整问题::: stackoverflow.com/questions/21416415/…
  • @Ryan:别忘了转义$value 变量$this->db->escape($value)。 @Muhammad:我们没有义务回答你的问题,请不要无礼。
  • 我完全同意@machineaddict 先生....非常感谢您的重要时间..先生
  • @Ryan Sir, (topic LIKE '%smart%' OR topic LIKE '%intelligent%' OR topic LIKE '%awesome%') 这对我有很大帮助.. 但最后我得到了 1 个额外的赞:: (topic LIKE '%smart%' OR topic LIKE '%intelligent%' OR topic LIKE '%awesome%') LIKE %%
【解决方案2】:

假设您使用的是 Codeigniter 2.1.4,正如您在 CodeIgniter active record documentation 中看到的那样,您不能将第二个参数作为数组传递给类似函数。您需要传递一个字符串作为参数。

$array_string = "smart,intelligent,awesome";
$array_like = explode(',', $array_string);

foreach ($array_like as $like)
{
    $this->db->like('topic', $like);
}

【讨论】:

  • 我已经尝试过这个.. 当我只通过一个值例如:smart 并且当我通过其中的 3 个或 2 个例如:smart,awesome,etc 时,这对我有用..
  • 那是因为您的数据库中可能没有任何匹配topic LIKE "%smart%" AND topic LIKE "%intelligent%" AND topic LIKE "%awesome%"
  • 然后将所有代码放入您的原始问题中。此外,如果您在执行后像 echo $this->db->last_query(); 这样打印查询并在 phpMyAdmin 中运行它可能会有所帮助。
猜你喜欢
  • 2014-04-05
  • 2012-10-02
  • 1970-01-01
  • 2014-07-18
  • 2014-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-22
相关资源
最近更新 更多