PHP:通过值项获取数组键。

PHP:通过值项获取数组键。,php,mysql,arrays,multidimensional-array,Php,Mysql,Arrays,Multidimensional Array,你好。我有一个多维数组 Array ( [0] => stdClass Object ( [id] => 1 [title] => "Title1") [1] => stdClass Object ( [id] => 3 [title] => "Title2") [2] => stdClass Object ( [id] => 4 [title] => "Title3") ) 如何从数组中按值获取

你好。我有一个多维数组

Array ( [0] => stdClass Object ( [id] => 1 [title] => "Title1")
        [1] => stdClass Object ( [id] => 3 [title] => "Title2")
        [2] => stdClass Object ( [id] => 4 [title] => "Title3")
      )
如何从数组中按值获取数组的编号

例如:如何使[2]在[id]=>1上具有[id]=>4或0?

简单搜索:

$id = 4;
foreach($array as $k=>$i) {
   if ($i->id == $id)
     break;
}

echo "Key: {$k}";

请注意,此解决方案可能比其他解决方案更快,因为它一找到就中断。

您可以创建一个新数组,通过迭代原始数组将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,这比每次迭代原始数组更有效

如果要从项目访问其他数据,可以将其存储在新数组中,而不必存储索引:

$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;

此函数在所有对象上运行,如果id与您提供的id匹配,则返回键

“投票需要15个声望”。我只有三个。
function GetKey($array, $value) {
    foreach($array as $key => $object) {
        if($object->id == $value) return $key;
    }
}

$key = GetKey($array, 4);