【问题标题】:PHP: Getting the array key by value entry.PHP:通过值条目获取数组键。
【发布时间】:2014-11-03 12:52:15
【问题描述】:
美好的一天。我有一个多维数组
Array ( [0] => stdClass Object ( [id] => 1 [title] => "Title1")
[1] => stdClass Object ( [id] => 3 [title] => "Title2")
[2] => stdClass Object ( [id] => 4 [title] => "Title3")
)
如何从数组中按值获取数组的个数。
例如:如何在 [id] => 1 上获得 [2] 的 [id] => 4 或 0 ?
【问题讨论】:
标签:
php
mysql
arrays
multidimensional-array
【解决方案1】:
天真的搜索:
$id = 4;
foreach($array as $k=>$i) {
if ($i->id == $id)
break;
}
echo "Key: {$k}";
请注意,此解决方案可能比其他答案更快,因为它一找到它就会中断。
【解决方案2】:
function GetKey($array, $value) {
foreach($array as $key => $object) {
if($object->id == $value) return $key;
}
}
$key = GetKey($array, 4);
此函数在所有对象上运行,如果 id 与您提供的匹配,则返回密钥。
【解决方案3】:
您可以通过迭代原始数组来创建一个新数组以将 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;