我有一个数组,类似于:
Array
(
[0] => Array
(
[questionid] => 21790
[name] => "________ would anyone hurt my poor cat?"
[userid] => 2
[firstname] => Admin
[category] => 69080
)
[1] => Array
(
[questionid] => 21770
[name] => Choose a suitable meaning of ‘bright’
[userid] => 2
[firstname] => Admin
[category] => 69053
)
[2] => Array
(
[questionid] => 21769
[name] => Choose the correct English word for: سمجھنا
[userid] => 2
[firstname] => Admin
[category] => 69053
)
...
...
...
...
...
)
我想在这个数组中搜索两个值questionid
和userid
,这些值位于如下数组中:
$questionids = array(23434, 33232, 33321);
$userids = array(2, 6, 33, 67, 88, 22, 43);
简而言之,我想要主数组中的每个这样的元素,它们的两个值(questionid和userid(位于数组$questionids
和$userids
中。
我尝试了很多解决方案,但还没有找到任何最佳的解决方案。如有任何帮助,我们将不胜感激。
来自评论
我试过:
function search( $array, $key, $value ) {
$results = array();
if ( is_array( $array ) ) {
if ( isset( $array[ $key ] ) && $array[ $key ] == $value ) {
$results[] = $array;
}
foreach ( $array as $subarray ) {
$results = array_merge( $results, search( $subarray, $key, $value ) );
}
}
return $results;
}
但上述解决方案的问题是,它需要单个键值对,而我有多个键值对要查找(都在不同的数组中(。
只需看看函数array_filter
,它应该非常适合您的需求。http://php.net/manual/en/function.array-filter.php:
$result = array_filter($array, "test_match", ARRAY_FILTER_USE_BOTH);
function test_match($key, $value){
$questionids = array(23434, 33232, 33321);
$userids = array(2, 6, 33, 67, 88, 22, 43);
return
in_array($value["userid"], $userids) && //user match?
in_array($value["questionid"], $questionids); //question match?
}
$result
现在将只包含符合条件的元素。
注意,我读了你的描述
简而言之,我想要主数组中的每个这样的元素,它们的两个值(questionid和userid(位于数组$questionids和$userid中。
作为CCD_ 7条件。如果需要匹配,只需返回
return
in_array($value["userid"], $userids) || //user match?
in_array($value["questionid"], $questionids); //question match?
如果要将参数$userids
和$questionids
作为参数传递,可以将它们封装在执行回调的对象中:
请参阅此处的文档:https://secure.php.net/manual/en/language.types.callable.php每个回调都支持一个数组(实例/方法名(,或者只支持第一个示例中的方法名。
class DataClosure{
private $qids;
private $uids;
function __construct($qids, $uids){
$this->uids = $uids;
$this->qids = $qids;
}
function test_match($key, $value){
return
in_array($value["userid"], $this->uids) && //user match?
in_array($value["questionid"], $this->qids); //question match?
}
}
代码为
$questionids = array(23434, 33232, 33321);
$userids = array(2, 6, 33, 67, 88, 22, 43);
$result = array_filter(
$array,
array(
new DataClosure($questionids, $userids),
"test_match"
),
ARRAY_FILTER_USE_BOTH);
$question = [];
$userid = [];
foreach($arr as $item){
array_push($question, $item->questionid);
array_push($userid , $item->userid);
}
var_dump($question );
var_dump($userid);
updated:导航到您的数组并获得您想要的值!简单如abc