Ale*_*lex 148 php arrays object
该数组看起来像:
[0] => stdClass Object
(
[ID] => 420
[name] => Mary
)
[1] => stdClass Object
(
[ID] => 10957
[name] => Blah
)
...
Run Code Online (Sandbox Code Playgroud)
我有一个名为的整数变量$v.
如何选择具有"ID"属性具有ID值的对象的数组条目?
Phi*_*hil 168
您可以迭代数组,搜索特定记录(仅在一次搜索中确定)或使用另一个关联数组构建哈希映射.
对于前者,这样的事情
$item = null;
foreach($array as $struct) {
if ($v == $struct->ID) {
$item = $struct;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
有关后者的更多信息,请参阅此问题和后续答案 - 通过多个索引引用PHP数组
Dan*_*rdt 63
YurkamTim是对的.它只需要修改:(抱歉,我现在无法发表评论).
在函数($)之后,您需要通过"use(&$ searchingValue)"指向外部变量,然后您可以访问外部变量.你也可以修改它.
$neededObject = array_filter(
$arrayOfObjects,
function ($e) use (&$searchedValue) {
return $e->id == $searchedValue;
}
);
Run Code Online (Sandbox Code Playgroud)
Tim*_*Tim 32
$arr = [
[
'ID' => 1
]
];
echo array_search(1, array_column($arr, 'ID')); // prints 0 (!== false)
Run Code Online (Sandbox Code Playgroud)
Yur*_*Tim 26
我在这里找到了更优雅的解决方案.适应问题可能如下:
$neededObject = array_filter(
$arrayOfObjects,
function ($e) {
return $e->id == $searchedValue;
}
);
Run Code Online (Sandbox Code Playgroud)
Mus*_*ful 12
如果需要多次查找,使用array_column重新索引将节省时间:
$lookup = array_column($arr, NULL, 'id'); // re-index by 'id'
Run Code Online (Sandbox Code Playgroud)
然后你可以随意$lookup[$id].
class ArrayUtils
{
public static function objArraySearch($array, $index, $value)
{
foreach($array as $arrayInf) {
if($arrayInf->{$index} == $value) {
return $arrayInf;
}
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
使用您想要的方式将是这样的:
ArrayUtils::objArraySearch($array,'ID',$v);
Run Code Online (Sandbox Code Playgroud)
解决了@YurkaTim的一个小错误,您的解决方案对我有用,但是添加了use:
要$searchedValue在函数内部使用,一种解决方案可以use ($searchedValue)在函数参数之后function ($e) HERE。
该array_filter函数仅$neededObject在条件为return时返回true
如果$searchedValue是字符串或整数:
$searchedValue = 123456; // Value to search.
$neededObject = array_filter(
$arrayOfObjects,
function ($e) use ($searchedValue) {
return $e->id == $searchedValue;
}
);
var_dump($neededObject); // To see the output
Run Code Online (Sandbox Code Playgroud)
如果$searchedValue是数组,我们需要检查列表:
$searchedValue = array( 1, 5 ); // Value to search.
$neededObject = array_filter(
$arrayOfObjects,
function ( $e ) use ( $searchedValue ) {
return in_array( $e->term_id, $searchedValue );
}
);
var_dump($neededObject); // To see the output
Run Code Online (Sandbox Code Playgroud)
尝试
$entry = current(array_filter($array, function($e) use($v){ return $e->ID==$v; }));
Run Code Online (Sandbox Code Playgroud)
这里的工作示例