如何根据 sql 结果分隔 php 数组


How to separate a php array based on sql results?

我有一个PHP数据数组(facebook用户ID),我想将其与存储在数据库中的数据(由数千个组成)进行比较。在数据库中找到的那些中,我希望将它们分成一个新的数组。我不知道该怎么做。

所以我从这个数组
开始

$ids = 3312312,1232424,1242234,2342636,457456,345345并以 2
结尾
$found = 34234234,234234234 $notfound = 23234234,234234,23423423

如果有人能帮忙,那就太好了。我已经以几种不同的方式开始了这个,但并没有走得很远。理想情况下,我希望一次完成此比较,但我不确定这是否可能。

谢谢!

编辑

根据您所说的内容,我快速提出了以下代码。这似乎是你得到的,但我无法慢慢建立到这一点,所以我不确定它是否正确。

<?php
$con=mysqli_connect("localhost","root","","sabotage");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
//json array is being posted to this file from another page
$jsonarray = '[{"name":"Lizzie OBrien","id":"218101335"},{"name":"Ellis Ward","id":"512376340"}]';
$friendlist = json_decode($jsonarray, true);
$found = [];
$notfound = [];
foreach($friendlist as $friend){
    $friendid = $friend['id'];
    $checkUserID = mysql_query("SELECT facebookid from users WHERE facebookid = '$friendid'");
    if (!$checkUserID) {
        die('Query failed to execute for some reason');
    }
    if (mysql_num_rows($checkUserId) > 0) {
        $found[] = $id;
    }else{
        $notfound[] = $id;
    }
}

mysqli_close($con);
?>

这给了我:

由于某种原因查询无法执行

我的 facebookid 列是整数有什么区别吗?

谢谢

我会怎么做:

$idsfromdb; //grab all ids from the db, and put in array
$idstobetested; //array of all ids you want to compare
$found = [];
$notfound[];
foreach($idstobetested as $id){
  if(in_array($id, $idsfromdb)){
    $found[] = $id;
  }else{
    $notfound[] = $id;
  }
}

然而:

看到您的评论后,如果您的数据库有大量记录,而不是将它们全部选中并放入数组中。相反,循环访问要测试的 id 数组并在数据库上运行选择查询,如果未返回 false,则该值存在于数据库中,然后您可以将 id 推送到找到的数组。

这可能有用: 如何检查 MySQL 数据库中是否已存在值

这是为我做的代码。没有你的帮助,我不可能做到。

<?php
$con=mysql_connect("localhost","root","");
// Check connection
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
//json array is being posted to this file from another page
$jsonarray = '[{"name":"Lizzie OBrien","id":"218101335"},{"name":"Ellis Ward","id":"512376340"}]';
$friendlist = json_decode($jsonarray, true);

$found = [];
$notfound = [];
foreach($friendlist as $friend){
    $friendid = $friend['id'];
    mysql_select_db("sabotage", $con);
    $result = mysql_query("SELECT facebookid FROM users WHERE facebookid ='$friendid'", $con);
    if (mysql_num_rows($result) > 0) {
        $found[] = $friendid;
    }else{
        $notfound[] = $friendid;
    }
}
mysql_close($con);
?>

您可能正在寻找此函数。

$jsonarray = '[{"name":"Lizzie OBrien","id":"218101335"},{"name":"Ellis Ward","id":"512376340"}]';
$friendlist = json_decode($jsonarray, true);
$friendIds = array_map( create_function('$data', 'return $data["id"];'), $friendlist);
// Will return all the matched records
$sql1 = "SELECT yourcolumnname FROM yourtablename WHERE facebookid IN (".implode(',', $friendIds).")";
// Will return all the unmatched records
$sql2 = "SELECT yourcolumnname FROM yourtablename WHERE facebookid NOT IN (".implode(',', $friendIds).")";