在php中查找数组中的匹配项
所以我有两个数组:在php中查找数组中的匹配项,php,array-intersect,Php,Array Intersect,所以我有两个数组: 1. $users_populated = users_populated: Array ( [0] => Array ( [id] => 10000106 [username] => [name] => [firstname] => [initial] => [su
1. $users_populated = users_populated: Array
(
[0] => Array
(
[id] => 10000106
[username] =>
[name] =>
[firstname] =>
[initial] =>
[surname] =>
)
[1] => Array
(
[id] => 10000106
[username] =>
[name] =>
[firstname] =>
[initial] =>
[surname] =>
[email] =>
[role] =>
[roleids] =>
[platform] =>
)
[2] => Array
(
[id] => 10000065
[username] =>
[name] =>
[firstname] =>
[initial] =>
[surname] =>
[email] =>
)
[3] => Array
(
[id] => 296
[username] =>
[name] =>
[firstname] =>
[initial] =>
[surname] =>
[email] =>
)
[4] => Array
(
[id] => 297
[username] =>
[name] =>
[firstname] =>
[initial] =>
[surname] =>
[email] =>
)
)
2. $user_list: Array
(
[0] => 10000106
[1] => 297
)
所以我想要第一个数组中与第二个数组匹配的值
即:
$output = output: Array
(
[0] => Array
(
[id] => 10000106
[username] =>
[name] =>
[firstname] =>
[initial] =>
[surname] =>
)
[1] => Array
(
[id] => 297
[username] =>
[name] =>
[firstname] =>
[initial] =>
[surname] =>
[email] =>
)
)
简而言之,第一个数组中的ID和第二个数组中的值应该匹配
我尝试过使用数组相交键,但没有成功
感谢阅读。使用:
-您的第二个数组是普通数组,因此它将直接在回调中起作用。当您要检查两个数组是否包含相同的值时, 无论值的顺序如何,都不能使用“==”或“==”。 试试这个功能
<?php
function array_equal($a, $b) {
return (is_array($a) && is_array($b) && array_diff($a, $b) === array_diff($b, $a));
}
?>
通过循环$users\u populated和array\u seach函数,您可以获得预期的结果
<?php
$output = array();
// Case 1: This will overlap by using the last appearance of the same ID value if repeated ID appears in $users_populated
foreach($users_populated as $value) {
if($key = array_search($value['id'], $user_list))
$output[$key] = $value;
}
// Case 2: This will use the first result found in $users_populated
foreach($users_populated as $value) {
if(empty($output[$value['id']]) && $key = array_search($value['id'], $user_list))
$output[$key] = $value;
}
var_dump($output);
谢谢。。。但很抱歉,我不熟悉这个功能。你能告诉我需要在$x和$y变量中添加什么吗?你不需要在那里添加任何东西。这是一个自给自足的代码,当我在我的Netbeans项目中使用这段代码时,会出现一个红色突出显示的错误“语言功能与项目设置中指示的PHP版本不兼容”。另外,代码位于名为“Groupcontroller.php”的控制器中。您的版本是什么?(请不要告诉我是5.2:\…)我的错。PHP也将在相同的数组元素之间使用比较回调。检查我的编辑(小提琴是)谢谢:)这正是我想要的:)
<?php
$output = array();
// Case 1: This will overlap by using the last appearance of the same ID value if repeated ID appears in $users_populated
foreach($users_populated as $value) {
if($key = array_search($value['id'], $user_list))
$output[$key] = $value;
}
// Case 2: This will use the first result found in $users_populated
foreach($users_populated as $value) {
if(empty($output[$value['id']]) && $key = array_search($value['id'], $user_list))
$output[$key] = $value;
}
var_dump($output);