加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 如何找到key为特定值的对象的索引?

发布时间:2020-12-13 17:12:05 所属栏目:PHP教程 来源:网络整理
导读:希望我说得对… 我怎么能找到ID = 68的索引? 我需要帮助创建一个返回索引2的函数…谢谢! $posts = Array ( [0] = stdClass Object ( [ID] = 20 [post_author] = 1 [post_content] = [post_title] = Carol Anshaw ) [1] = stdClass Object ( [ID] = 21 [pos
希望我说得对…

我怎么能找到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',))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读