[英]How can I find index of an object where key is a specific value?
希望我說得對...
我怎么能找到ID = 68的索引?
我需要幫助創建一個返回索引2的函數...謝謝!
$posts = Array (
[0] => stdClass Object
(
[ID] => 20
[post_author] => 1
[post_content] =>
[post_title] => Carol Anshaw
)
[1] => stdClass Object
(
[ID] => 21
[post_author] => 1
[post_content] =>
[post_title] => Marie Arana
)
[2] => stdClass Object
(
[ID] => 68
[post_author] => 1
[post_content] =>
[post_title] => T.C. Boyle
)
[3] => stdClass Object
(
[ID] => 1395
[post_author] => 1
[post_content] =>
[post_title] => Rosellen Brown
)
)
創建一個遍歷數組的簡單函數
封裝它而不是讓它懸掛
在粘貼社區的數據結構時, 請記住使用var_export而不是print_r
你可以做這么簡單的功能:
function getKeyForId($id, $haystack) {
foreach($haystack as $key => $value) {
if ($value->ID == $id) {
return $key;
}
}
}
$keyFor68 = getKeyForId(68, $posts);
但是讓特定功能懸而未決是沒有意義的。 你可以這樣使用ArrayObject :
class Posts extends ArrayObject {
public function getKeyForId($id) {
foreach($this as $key => $value) {
if ($value->ID == $id) {
return $key;
}
}
}
}
用法示例:
$posts = new Posts();
$posts[] = new StdClass();
$posts[0]->ID = 1;
$posts[0]->post_title = 'foo';
$posts[] = new StdClass();
$posts[1]->ID = 68;
$posts[1]->post_title = 'bar';
$posts[] = new StdClass();
$posts[2]->ID = 123;
$posts[2]->post_title = 'test';
echo "key for post 68: ";
echo $posts->getKeyForId(68);
echo "\n";
var_export($posts[$posts->getKeyForId(68)]);
輸出:
key for post 68: 1
stdClass::__set_state(array(
'ID' => 68,
'post_title' => 'bar',
))
function findIndexById($id, $array) {
foreach($array as $key => $value) {
if($value->ID == $id) {
return $key;
}
}
return false;
}
你可以像findIndexById(68, $array);
一樣搜索它findIndexById(68, $array);
這將返回數組的索引,如果它發現否則為false。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.