Php 如何查找键为特定值的对象的索引?

Php 如何查找键为特定值的对象的索引?,php,wordpress,Php,Wordpress,希望我说得对 我怎样才能找到ID=68的索引 我需要帮助创建一个函数,将返回索引2。。。谢谢 $posts = Array ( [0] => stdClass Object ( [ID] => 20 [post_author] => 1 [post_content] => [post_title] => Carol Anshaw

希望我说得对

我怎样才能找到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
        )
)
  • 生成一个在数组上迭代的普通函数

  • 封装它而不是挂起它

  • 为社区粘贴数据结构时,请记住使用而不是打印

  • 您可以创建这样一个简单的函数:

    function getKeyForId($id, $haystack) {
        foreach($haystack as $key => $value) {
            if ($value->ID == $id) {
                return $key;
            }
        }
    }
    
    $keyFor68 = getKeyForId(68, $posts);
    
    但让特定函数挂起是没有意义的。您可以这样使用:

    用法示例:

    $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',
    ))
    

    您可以像下面这样搜索它
    findIndexById(68,$array)
    如果发现其他错误,它将返回数组的索引。

    这可能是
    $index=$posts[2]
    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;
    }