繁体   English   中英

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

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

我有一个如下所示的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;

提前致谢!

首先,您的json是具有movies属性的对象。 因此,您必须在通过获取movies属性进行解码时才能获取电影。 然后,如果json_decode第二个参数为true,则返回关联的数组而不是对象。 如果要获取对象,请这样调用:

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

最后,您要获得名称为title且值强制转换的数组。

您可以使用以下代码:

$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就像一个数组,而不是像第二个参数一样将true传递给json_decode()

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM