美好的一天。我有一个多维数组
Array ( [0] => stdClass Object ( [id] => 1 [title] => "Title1")
[1] => stdClass Object ( [id] => 3 [title] => "Title2")
[2] => stdClass Object ( [id] => 4 [title] => "Title3")
)
如何从数组中获取数组的数字。
例如:如何获得[2] [id] => [id] =>上的4或0 1?
答案 0 :(得分:1)
天真的搜索:
$id = 4;
foreach($array as $k=>$i) {
if ($i->id == $id)
break;
}
echo "Key: {$k}";
请注意,此解决方案可能比其他答案更快,因为它会在找到后立即中断。
答案 1 :(得分:1)
function GetKey($array, $value) {
foreach($array as $key => $object) {
if($object->id == $value) return $key;
}
}
$key = GetKey($array, 4);
此函数遍历所有对象,如果id与您提供的id匹配,则返回密钥。
答案 2 :(得分:0)
您可以通过迭代原始数组来创建一个新数组以将ID映射到索引:
$map = [];
foreach($array as $key=>$value)
$map[$value->id]=$key;
echo 'object with id 4 is at index ' . $map[4];
echo 'object with id 1 is at index ' . $map[1];
如果你想要查找多个id,这比每次迭代原始数组更有效。
如果要从ojects访问其他数据,可以将它们存储在新数组中,存储索引的内容:
$objects = [];
foreach($array as $obj)
$objects[$obj->id]=$obj;
echo 'object with id 4 has the following title: ' . $obj[4]->title;
echo 'object with id 1 has the following title: ' . $obj[1]->title;