2012-12-07 35 views
-1

可能重複:
Remove index key from Array for accessing to object?從陣列中取出指數

我需要能夠訪問term_id價值,但我不知道用數組assossiated數量或索引。我怎樣才能訪問它?

我將訪問它像這樣$value->term_id,現在我需要通過將數的值($value->[26]->term_id)後才能訪問它。

Array 
(
    [26] => stdClass Object 
     (
      [term_id] => 26 
      [name] => Night Life. 
      [slug] => shopping-and-night-life 
      [term_group] => 0 
      [term_taxonomy_id] => 28 
      [taxonomy] => map_categories 
      [description] => Most of the late night clubs, bars and pubs in Victoria are situated downtown. Here are a few to check out: 
      [parent] => 0 
      [count] => 6 
      [object_id] => 925 
     ) 

) 
+3

簡單的解決方案:'$ value = $ value [26]; echo $ value-> term_id;'這是因爲你有一個內部有一個對象的數組。 – phpisuber01

+0

'stdClass'是_object_,所以用' - >' –

+0

訪問點是他不知道26索引/// –

回答

0

你必須要麼尋找它OR寫一個算法,讓你不會失去它擺在首位。

1

現在它是一個數組,所以你會喜歡這個訪問:$value[26]->term_id如果你不希望有放你只需要設置另一個變量等於數組對象裏面的關鍵是:

$value2 = $value[26]; 
echo $value2->term_id; 

如果你不知道,如果值26然後使用foreach。

foreach($value as $key => $val) { 
    $term_id = $val->term_id; 
} 

,如果你知道那裏是數組中只有一個元素,你可以這樣做:

$value2 = end($value); 
$term_id = $value2->term_id; 
4

你可以使用array_values()「重置」的數組的下標:

$new = array_values($old); 

將導致具有

Array 
(
    [0] => stdClass Object 
     (
      [term_id] => 26 
      [name] => Night Life. 
      [slug] => shopping-and-night-life 
      [term_group] => 0 
      [term_taxonomy_id] => 28 
      [taxonomy] => map_categories 
      [description] => Most of the late night clubs, bars and pubs in Victoria are situated downtown. Here are a few to check out: 
      [parent] => 0 
      [count] => 6 
      [object_id] => 925 
     ) 

) 

無論以前的數組索引是什麼。

+0

謝謝,我也通過做$ i = array_keys($ cat)來嘗試它,而且這也起作用了! – user990717