如何通过php解析此json文件?

Awah Hammad |

我试图使用php解析包含我商店产品的json文件,但是没有运气!我是php的新手,我尝试过在线搜索,但没有答案。这是我的json文件的一部分:

    [
  {
    "_type": "default",
    "description": [
      "Product Description comes here"
    ],
    "url": "here is the url to my seo friendly url",
    "price": [
      "11.64"
    ],
    "sizes": [
      "sizes come here"
    ],
    "images": [
      "image name and address is here"
    ],
    "_template": "5c1333451e128f546e451197f6c6061b3a66d1ee",
    "_cached_page_id": "5119b553b1512ae1a19d6cd0d3f29e51e111a90c",
    "name": [
      "product name is here"
    ]
  },
  {
    "_type": "default",
    "description": [
      "Product #2 Description comes here"
    ],
    "url": "here is the url to my seo friendly url",
    "price": [
      "11.64"
    ],
    "sizes": [
      "sizes come here"
    ],
    "images": [
      "image name and address is here"
    ],
    "_template": "5c1333451e128f546e451197f6c6061b3a66d1ee",
    "_cached_page_id": "5119b553b1512ae1a19d6cd0d3f29e51e111a90c",
    "name": [
      "product #2 name is here"
    ]
  }
]

这只是整个json文件的示例,但它遵循这种格式。我尝试编写以下php代码对其进行索引,但正如我所说,没有运气:

    <?php
// this code reads from the files provided to it and populates the     database with products

$jsondata = file_get_contents("55products.json");
$json = json_decode($jsondata, true);


foreach ($json["products"] as $product)
{
    // now lets split it into smaller pieces
    foreach ($product as $product_infos) {
        print_r($product_infos);
        echo "<br /><br /><br />";


    }

}

但是仍然无法访问内容或具体来说,我不知道如何访问其中的数据存储。我知道这可能是一个非常愚蠢的问题,但是所有在线教程都没有类似的语法,因此请帮助我。最好的祝福。

亚历克斯·安德烈(Alex Andrei)

内部元素本身就是数组,您需要使用索引0访问值

$obj = json_decode($json,true);
// var_dump($obj);exit;

foreach ($obj as $product)
{
    print $product["description"][0] . "<br/>";
    print $product["images"][0] . "<br/>";
    print $product["url"] . "<br/>";
    print $product["name"][0] . "<br/>";
}

将输出

Product Description comes here
image name and address is here
here is the url to my seo friendly url
product name is here
Product #2 Description comes here
image name and address is here
here is the url to my seo friendly url
product #2 name is here

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章