2013-03-15 156 views
2

嘿,我想從電影API中獲取數據。格式是這樣的:PHP獲取第一個數組元素

page => 1 
results => 
    0 => 
    adult => 
    backdrop_path => /gM3KKixSicG.jpg 
    id => 603 
    original_title => The Matrix 
    release_date => 1999-03-30 
    poster_path => /gynBNzwyaioNkjKgN.jpg 
    popularity => 10.55 
    title => The Matrix 
    vote_average => 9 
    vote_count => 328 
    1 => 
    adult => 
    backdrop_path => /o6XxGMvqKx0.jpg 
    id => 605 
    original_title => The Matrix Revolutions 
    release_date => 2003-10-26 
    poster_path => /sKogjhfs5q3aEG8.jpg 
    popularity => 5.11 
    title => The Matrix Revolutions 
    vote_average => 7.5 
    vote_count => 98 
etc etc.... 

我怎樣才能只有第一元件[0]的數據(如在backdrop_path,ORIGINAL_TITLE,等等等等)?我是新的PHP陣列:)。

當然,這並是我用來輸出我的陣列數據:

print_r($theMovie) 

任何幫助將是巨大的!

+3

是'...-> results [0]'好嗎? – Voitcus 2013-03-15 16:07:34

+0

你似乎在回答你自己的問題... $ theMovie [「results」] [0]? – cernunnos 2013-03-15 16:08:00

+0

請參閱http://stackoverflow.com/questions/1921421/get-the-first-element-of-an-array/24802579#24802579 – 2014-07-18 18:19:03

回答

2

您可以指向數組與此$theMovie['result'][0]['backdrop_path'];或可以循環通過像這樣,

foreach($theMovie['results'] as $movie){ 
    echo $movie['backdrop_path']; 
} 
+0

我沒有從上面的代碼中獲取任何數據,但是我得到的數據是** $ theMovie ['result'] [0] ['backdrop_path']; ** ?? – StealthRT 2013-03-15 16:21:32

+0

是的,我錯過了一些檢查一遍。 – 2013-03-15 16:25:31

+0

謝謝!現在工作得很好。 – StealthRT 2013-03-15 16:28:26

1

假設所有這些代碼被存儲在一個變量$datas

$results = $datas['results']; 
$theMovie = $results[0]; 
+0

給你+1,幫助我,zessx! – StealthRT 2013-03-15 16:28:45

1

嘗試

$yourArray['results'][0] 

但是要記住,當結果數組爲空,這樣會產生誤差。

+0

給你+1,幫助我,nekaab! – StealthRT 2013-03-15 16:29:21

5

另一種解決方案:

$arr = reset($datas['results']); 

返回第一個數組元素的值,或FALSE如果數組是空的。

OR

$arr = current($datas['results']); 

電流()函數簡單地返回,因此目前正由內部指針指向的數組元素的值。它不會以任何方式移動指針。如果內部指針超出元素列表的末尾或數組爲空,則current()返回FALSE。

+0

給你+1,幫助我,瓦列裏五! – StealthRT 2013-03-15 16:30:31

1

您可以使用array_shift彈出第一個元素,然後檢查它是否有效(如果沒有結果或者該項不是數組,則返回array_shift將返回null)。

$data = array_shift($theMovie['results']); 
if (null !== $data) { 
    // process the first result 
} 

如果你想要遍歷儘管所有的結果,你可以做一個foreach循環while循環與array_shift

foreach($theMovie['results'] as $result) { 
    echo $result['backdrop_path']; 
} 

while ($data = array_shift($theMovie['results'])) { 
    echo $data['backdrop_path']; 
} 

或者只是使用$theMovie['result'][0]['backdrop_path'];作爲已經建議,檢查$theMovie['result'][0]實際上是設置後。

+0

給你+1幫助我,達人C.! – StealthRT 2013-03-15 16:30:50

相關問題