in_array函数,由于某种原因,返回false;
这是我正在使用的代码:
$query = "SELECT users_invites.invite_user_id
FROM users_invites
JOIN users ON users.id = users_invites.user_id AND users_invites.user_id =". param('session_id')."
ORDER BY users.id ASC";
$response = $this->_db->query($query)->result_array();
foreach ($response as $key => $value)
{
if (!in_array($_REQUEST['invite_user_id'][$key],$response[$key]))
$this->_db->insert("users_invites",array("user_id"=> param('session_id') , "invite_user_id"=>$_REQUEST['invite_user_id'][$key]));
}
in_array函数不起作用,插入命令总是执行。 有什么想法吗?
P.S: invite_user_id是一个数组。 修改:响应值为:
Array
(
[0] => Array
(
[invite_user_id] => 20
)
[1] => Array
(
[invite_user_id] => 19
)
[2] => Array
(
[invite_user_id] => 3
)
)
$ _REQUEST ['invite_user_id']值:
Array
(
[0] => 3
[1] => 4
)
答案 0 :(得分:1)
鉴于你得到的结构,我会对数据进行foreach
将其分解为单个数组,并从表中返回所有id。
从那里我foreach
$_REQUEST['invite_user_id']
对阵新阵列$ids
,这是一个示例:
$ids = array();
foreach ($response as $item)
{
$ids[] = $item['invite_user_id'];
}
foreach ($_REQUEST['invite_user_id'] as $id)
{
if (!in_array($id, $ids))
{
echo "{$id} was not found...\n";
}
else
{
echo "{$id} was found...\n";
}
}
<强> And here is a live DEMO. 强>
答案 1 :(得分:0)
您的请求应该是这样的
$query = "SELECT users_invites.invite_user_id
FROM users_invites
JOIN users ON users.id = users_invites.user_id AND users_invites.user_id =". param('session_id')."
ORDER BY users.id ASC";
$response = $this->_db->query($query)->result_array();
$invite_user_id = array();
foreach ($response as $key => $value)
{
$invite_user_id[] = $value;
}
foreach( $_REQUEST['invite_user_id'] AS $key => $value )
{
if ( !in_array( $value,$invite_user_id) )
{
$this->_db->insert("users_invites",array("user_id"=> param('session_id') , "invite_user_id"=> $value));
}
}
答案 2 :(得分:0)
以下内容应该运作良好:
$query = 'SELECT users_invites.invite_user_id
FROM users_invites
JOIN users ON users.id = users_invites.user_id AND
users_invites.user_id = ' . param('session_id') . '
ORDER BY users.id ASC';
$response = $this->_db->query($query)->result_array();
$storedInvites = array();
foreach ($response as $index => $data) {
$storedInvites[] = $data['invite_user_id'];
}
foreach ($_REQUEST['invite_user_id'] as $index => $inviteUserId) {
if (!in_array($inviteUserId, $storedInvites)) {
$insertData = array(
'user_id' => param('session_id'),
'invite_user_id' => $inviteUserId
);
$this->_db->insert('users_invites', $insertData);
}
}