让我们说我们有一个例如来自预览问题的数组...我怎样才能找到 [X] => stdClass对象如果我们知道这个对象的[id]是[id] => 9 ???
Array
(
[0] => stdClass Object
(
[id] => 8
[book_category] => C Program
[book_id] => 2
[book_name] => C Language
[book_category_id] => 8
[book_in_stock] => 5
)
[1] => stdClass Object
(
[id] => 8
[book_category] => C Program
[book_id] => 1
[book_name] => C++
[book_category_id] => 8
[book_in_stock] => 10
)
[X] => stdClass Object
(
**[id] => 9**
[book_category] => English
[book_id] => 3
[book_name] => Comp Eng
[book_category_id] => 9
[book_in_stock] => 5
)
[3] => stdClass Object
(
[id] => 9
[book_category] => English
[book_id] => 4
[book_name] => Eng English
[book_category_id] => 9
[book_in_stock] => 5
)
)
答案 0 :(得分:1)
或使用array_filter:
$result=array_filter($array, function($x) {
return $x->id == 9;
});
将返回ID为9的所有对象。如果id是唯一的,则可以使用$result[0]
访问该对象。
答案 1 :(得分:0)
你必须走很长的路,并搜索数组的每个元素:
foreach( $array as $key => $array_element ) {
if( $array_element-> id == 9 ) {
// Do what you want here. The value you're looking for is in $key.
}
}
答案 2 :(得分:0)
在PHP 7上:
$key = array_search( 9, array_column( $array, 'id' ) );
在PHP< 7请参阅其他答案,或 - 如果您想要模拟array_column
:
function array_column2( $array, $column )
{
return array_map
(
function( $row ) use( $column )
{
return is_object( $row ) ? $row->$column : $row[$column];
}
, $array
);
}
$key = array_search( 9, array_column2( $array, 'id' ) );
的 3v4l.org demo 强>