2012-05-17 77 views
4

希望我正確地說這個...如何找到鍵是特定值的對象的索引?

我怎麼能找到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 
     ) 
) 
+0

難道這是'$ index = $ posts [2]'? –

回答

4
  1. 做一個平凡函數該陣列上迭代

  2. 封裝它而不是把掛

  3. 記住使用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', 
)) 
0
function findIndexById($id, $array) { 
    foreach($array as $key => $value) { 
     if($value->ID == $id) { 
      return $key; 
     } 
    } 
    return false; 
} 

,你可以搜索像這樣findIndexById(68, $array);這將返回索引如果發現數組錯誤,則返回數組。

相關問題