PHP:从JSON文件中按键从数组中获取子数组数据的子数组

时间:2017-06-04 17:03:02

标签: php json php-7.1

我有一个JSON文件,如下所示,我已经想要创建一个以电影名称为键的最终数组,而actor是键存储的值

JSON文件

{
    "movies": [{
            "title": "Diner",
            "cast": [
                "Steve Guttenberg",
                "Daniel Stern",
                "Mickey Rourke",
                "Kevin Bacon",
                "Tim Daly",
                "Ellen Barkin",
                "Paul Reiser",
                "Kathryn Dowling",
                "Michael Tucker",
                "Jessica James",
                "Colette Blonigan",
                "Kelle Kipp",
                "Clement Fowler",
                "Claudia Cron"
            ]
        },
        {
            "title": "Footloose",
            "cast": [
                "Kevin Bacon",
                "Lori Singer",
                "Dianne Wiest",
                "John Lithgow",
                "Sarah Jessica Parker",
                "Chris Penn",
                "Frances Lee McCain",
                "Jim Youngs",
                "John Laughlin",
                "Lynne Marta",
                "Douglas Dirkson"
            ]
        }
    ]
}

理想输出

Array(
["Diner"]=>Array(Steve Guttenberg","Daniel Stern","Mickey Rourke","Kevin Bacon","Tim Daly","Ellen Barkin","Paul Reiser","Kathryn Dowling","Michael Tucker","Jessica James","Colette Blonigan","Kelle Kipp","Clement Fowler","Claudia Cron")
["Footloose"]=>Array("Kevin Bacon","Lori Singer","Dianne Wiest","John Lithgow","Sarah Jessica Parker","Chris Penn","Frances Lee McCain","Jim Youngs","John Laughlin","Lynne Marta","Douglas Dirkson")

到目前为止我的代码

$movies = json_decode(file_get_contents("movies.json"),true);

$actors = array();
foreach($movies as $movie){
  $key = "cast";
  echo $movie->$key;
}

但是,当我运行我当前的代码时,php会给我一个通知" 尝试获取非对象的属性"有人可以解释为什么会这样,以及如何解决它?错误在这一行:

echo $movie->$key;

提前感谢!

2 个答案:

答案 0 :(得分:1)

首先,你的json是具有movies属性的对象。所以你必须通过获取movies属性来解码时获得电影。 然后,如果json_decode的第二个参数为true,则返回关联的数组而不是对象。如果你想获得对象,请这样调用:

$json = json_decode(file_get_contents("movies.json"));
$movies = $json->movies;

最后你想获得名称为title的数组,并且值为cast。

您可以使用以下代码:

$json = json_decode(file_get_contents("movies.json"));
$movies = $json->movies;

$actors = array();
foreach($movies as $movie){
    $title = $movie->title;
    $actors[$title] = $movie->cast;
}

print_r($actors); //to see ideal output

答案 1 :(得分:1)

这是未经测试的,但请尝试这样的事情。 (注意访问$movies就像一个数组,而不是传递true作为json_decode()的第二个参数的对象

$movies = json_decode(file_get_contents("movies.json"), true);

$actors = array();
foreach($movies['movies'] as $movie){
  $actors[$movie['title']] = $movie['cast'];
}