Json to PHP - 如何从嵌套在一个更大的数组中的数组中获取特定值

问题描述:

我想使用TheMovieDatabase API将一些信息放到我的脚本上。 我正确解码使用Json to PHP - 如何从嵌套在一个更大的数组中的数组中获取特定值

$data['moviecrew'] = json_decode($movie_crew); 

现在,$数据[“moviecrew”]数组是以下的输出:

"crew":[{"credit_id":"52fe43409251416c750094c5","department":"Directing","id":59026,"job":"Director","name":"Peyton Reed","profile_path":"/h9lEnyQ60EjKRT3ZAOcrqQVlwn3.jpg"},{"credit_id":"52fe43409251416c750094f3","department":"Writing","id":52934,"job":"Screenplay","name":"Nicholas Stoller","profile_path":"/qwcx9bdVhmyjWb0KOCdRHDXoFZ9.jpg"},{"credit_id":"52fe43409251416c750094f9","department":"Writing","id":62763,"job":"Screenplay","name":"Jarrad Paul","profile_path":"/qWaXQi5Pz6jEKw9E2xRuX74phiB.jpg"}, ..

我想什么做的是采取“主任“名字放在我的PHP脚本中。 我尝试下面的代码:

<?php if($moviecrew->crew->job == "Director"){echo $moviecrew->crew->name;} ?> 

遗憾的是它不工作,它给了我下面的错误:

A PHP Error was encountered Severity: Notice Message: Trying to get property of non-object Filename: film/filmsheet.php Line Number: 36 Backtrace: File: /Applications/XAMPP/xamppfiles/htdocs/domain.com/application/views/film/filmsheet.php Line: 36 Function: _error_handler File: /Applications/XAMPP/xamppfiles/htdocs/domain.com/application/controllers/Film.php Line: 106 Function: view File: /Applications/XAMPP/xamppfiles/htdocs/domain.com/index.php Line: 315 Function: require_once

线36只是:

<?php if($moviecrew->crew->job == "Director"){echo $moviecrew->crew->name;} ?> 

怎么可能我解决了这个问题?感谢您的善意支持。

有几件事,其中之一可能是代码示例中的复制/粘贴错误。

起初你有$data['moviecrew']然后你尝试和使用变量$moviecrew这是不存在于你的问题。 (它是存在于代码?)

假设你已经做了$moviecrew = $data['moviecrew'],你会遇到以下问题:

“船员”是一个数组不是一个对象,所以你需要循环在他们所有。

但要提取只是导演的名字,所以如果我们假设总有永远只能一个导演: -

$director = null; 

foreach ($moviecrew->crew as $crewMember) { 
    if ($crewMember->job === 'Director') { 
     $director = $crewMember->name; 
     break; 
    } 
} 

if (!is_null($director)) { 
    echo $director; 
} 
+0

完美的,它就像一个魅力!谢谢bcmcfc :)关于你的亮点,我使用的是Codeigniter框架。 $ data ['moviecrew']已经在Controller中声明。在声明$ data对象后,我可以将它分配给特定的页面,使用$ this-> load-> view('film/filmsheet',$ data)。通过这种方式,我可以使用像$ moviecrew这样的$ data ['moviecrew']对象。 – mauro269