2013-03-15 179 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

相关问题