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

PHP: get subarray of subarray data from array by key from JSON file

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

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 给我一个通知“Trying to get 属性 of non-object” 可以有人解释为什么会这样以及如何解决?错误在这一行:

echo $movie->$key;

提前致谢!

首先,您的 json 是 object,它有 movies 属性。所以你必须在通过获取 movies 属性 解码时获取电影。 然后,如果 json_decode 的第二个参数为真,则它 returns 关联数组而不是 object。如果你想得到object,这样调用:

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

最后,您想要获得名称为标题且值已转换的数组。

您可以使用以下代码:

$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

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

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

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