这就是我的数组的样子:
array(3) {
[0]=>
string(3) "600"
[1]=>
string(3) "601"
[2]=>
string(3) "603"
}
这是我的对象的样子:
array(7) {
[0]=>
object(stdClass)#688 (6) {
["id"]=>
string(3) "601"
["name"]=>
string(10) "test8opkpo"
["avatar"]=>
string(85) "http://avatars/user/medium.png"
["url"]=>
string(86) "/index.php"
["isOnline"]=>
int(0)
["lastseen"]=>
string(11) "2 weeks ago"
}
[1]=>
object(stdClass)#689 (6) {
["id"]=>
string(3) "604"
["name"]=>
string(6) "nopita"
["avatar"]=>
string(85) "http://avatars/user/medium.png"
["url"]=>
string(82) "/index.php"
["isOnline"]=>
int(0)
["lastseen"]=>
string(10) "1 week ago"
}
[2]=>
object(stdClass)#690 (6) {
["id"]=>
string(3) "603"
["name"]=>
string(6) "test_b"
["avatar"]=>
string(85) "http://avatars/user/medium.png"
["url"]=>
string(82) "/index.php"
["isOnline"]=>
int(0)
["lastseen"]=>
string(11) "6 hours ago"
}
现在我想从对象中删除每个项目的ID,它与数组中的值匹配。
因此,对象的最终输出不应包含给定数组中的id。怎么做?
我尝试使用array_diff_key
和unset
无效。
$contactArray[$i]
代表对象中的每个id
if (in_array($contactArray[$i], $array)) {
$a = array_diff_key($results->contacts, [$i => $contactArray[$i]]);
}
答案 0 :(得分:1)
我创建了自己的一组示例来模拟您希望在阵列上发生的事情:
$x = array('600','601', '603');
$y = array(
array("id" => "600",
"name" => "test",
"avatar" => "image"
),
array("id" => "601",
"name" => "test1",
"avatar" => "image1"
),
array("id" => "602",
"name" => "test2",
"avatar" => "image2"
),
array("id" => "603",
"name" => "test3",
"avatar" => "image3"
),
array("id" => "604",
"name" => "test4",
"avatar" => "image4"
)
);
echo '<pre>';
var_dump($y);
echo '</pre>';
$new_arr_ = array();
for($i = 0, $ctr = count($y); $i < $ctr; $i++) {
if(!in_array($y[$i]["id"], $x)) {
$new_arr_[] = array($y[$i]["id"], $y[$i]["name"], $y[$i]["avatar"]);
}
}
echo '<pre>';
var_dump($new_arr_);
echo '</pre>';
希望它有所帮助。
答案 1 :(得分:0)
如果我理解正确,以下内容应该有效:
$contactArray = array_filter($contactArray, function ($v) use ($array) {
return !in_array(isset($v->id)?$v->id:null, $array);
});