[英]How can i check if a value is in codeigniter result_array()
I am having a hard time with this.我很难做到这一点。 Although am new here.
虽然我是新来的。 I am using Codeigniter, This is the query code.
我正在使用 Codeigniter,这是查询代码。
<?php
$is_member = $this->db->query("SELECT user FROM chatroom_members WHERE room='$row->id'");
$check = $is_member->result_array();
if (in_array($id, $check)) {
echo "Match found";
} else {
echo "Match not found";
}
?>
Which outputs Match not found未找到匹配的输出
but print_r($check)
gives但
print_r($check)
给出
Array ( [0] => Array ( [user] => 1 ) [1] => Array ( [user] => 2 )
So how am I going to check if a specific integer is in the array which is multidimensional I think.那么我将如何检查一个特定的整数是否在我认为是多维的数组中。
Note: $id = 1, which is clearly in the array, but it still saying not found.注意:$id = 1,明明在数组中,却还是提示找不到。 Any answers?
任何答案? feel free to correct me if am doing something wrong
如果我做错了什么,请随时纠正我
I think the best way to do it is having a foreach loop, in_array wouldn't work on the root array.我认为最好的方法是使用 foreach 循环, in_array 不适用于根数组。
<?php
$is_member = $this->db->query("SELECT user FROM chatroom_members WHERE room='$row->id'");
$arrays = $is_member->result_array();
$found = false;
foreach ($arrays as $array) {
if(in_array($id,$array)) {
$found = true;
break;
}
}
echo $found === true ? "Match found" : "Match not found";
?>
If you already know the ID you're looking for and the room ID where you want to check, you might benefit from doing this:如果您已经知道要查找的 ID 和要检查的房间 ID,您可能会从这样做中受益:
(I'm assuming here that the room number is contained in $row->id
and the user ID you're looking for is $id
) (我在这里假设房间号包含在
$row->id
,您要查找的用户 ID 是$id
)
$this->db->select('user');
$this->db->from('chatroom_members');
$this->db->where('room', $row->id);
$this->db->where('user', $id);
$query = $this->db->get();
return ($query->num_rows() == 0) ? false : true;
You'll save yourself from looping through a huge result array (which may or may not be an issue depending on how large the resultset from the table is) and you'll get a simple yes/no answer.您将免于遍历巨大的结果数组(这可能是也可能不是问题,具体取决于表中的结果集有多大),并且您将得到一个简单的是/否答案。 I used a
return
and a ternary operator but you can easily change that to an if/else and do something else than return true or false depending on what you need.我使用了
return
和三元运算符,但您可以轻松地将其更改为 if/else 并根据您的需要执行除返回 true 或 false 之外的其他操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.