知道为什么这不起作用?我收到了用户设置的标签,并希望获得具有相同标签的其他用户ID。
控制器:
$this->load->model('tag_model');
$data['usr_tags'] = $this->tag_model->get_home_tags($user_id);
$tags = $this->tag_model->get_home_tags($user_id);
$tag_array = $tags;
$data['tag_users'] = $this->tag_model->get_tag_users($tag_array);
型号:
function get_tag_users($tag_array)
{
//$tag = array('item1','item2','item3');
$tag = $tag_array;
$query_str = 'SELECT DISTINCT user_id FROM tags WHERE tag IN ("'. implode('","', $tag) .'")';
$query = $this->db->query($query_str);
if($query->num_rows() > 0) {
foreach($query->result_array() as $tag_users) {
$data[] = $tag_users;
}
return $data;
}else{
return false;
}
}
错误:
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: models/tag_model.php
Line Number: 20
答案 0 :(得分:3)
<强>控制器强>
$this->load->model('tag_model');
$data['usr_tags'] = $this->tag_model->get_home_tags($user_id);
$data['tag_users'] = $this->tag_model->get_tag_users($data['usr_tags']);
<强>模型强>
function get_tag_users($tag_array)
{
$tags=array();
foreach($tag_array as $tag)
{
$tags[]= $tag['tag'];
}
$query_str = 'SELECT DISTINCT user_id FROM tags WHERE tag IN ('.implode(",", $tags).')';
$query = $this->db->query($query_str);
if($query->num_rows() > 0)
{
return $query->results();
}
else
{
return false;
}
}
注意:您的$data['tag_users']
将包含另一个用户ID数组。
答案 1 :(得分:2)
您的$tag_array
看起来像这样:
array(4){
[0]=> array(1){
["tag"]=> string(3) "lol"
}
[1]=> array(1){
["tag"]=> string(4) "here"
}
[2]=> array(1){
["tag"]=> string(3) "php"
}
[3]=> array(1){
["tag"]=> string(5) "mysql"
}
}
它实际上是一个数组数组,你不能在它上面使用implode
。发生“Array to string”转换是因为数组的每个元素都是一个数组,PHP需要将其转换为字符串才能“内爆”它们。
您可以使用array_map
从阵列中获取每个标记。
function get_tag_users($tag_array)
{
$tag = array_map(function($a){
return $a['tag'];
}, $tag_array);
$query_str = 'SELECT DISTINCT user_id FROM tags WHERE tag IN ("'. implode('","', $tag) .'")';
如果你没有PHP 5.3,你可以这样做:
function get_tag_users($tag_array)
{
$tag = array_map(create_function('$a', 'return $a["tag"];'), $tag_array);
$query_str = 'SELECT DISTINCT user_id FROM tags WHERE tag IN ("'. implode('","', $tag) .'")';