2015-12-08 71 views
0

我試圖解析這個json文件,它有我的商店的產品使用php,但沒有運氣!我是新來的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 />"; 


    } 

} 

但仍然無法訪問的內容或具體而言,我不知道如何訪問數據存儲在那裏。我知道這可能是一個非常愚蠢的問題,但所有在線教程都沒有類似的語法,所以請幫助我。 此致敬禮。

+0

您張貼到正確格式化看起來JSON(我自己通過'json_encode'試過了,這很好。)你在問如何訪問裏面的數據嗎?你讓'json_encode'返回數據而不是'stdClass Object's,所以你只需要''product_infos' –

+0

@ChrisSprague謝謝是的,我的問題是獲取內部數組數據我真的不知道如何獲得!那些提取我的舊網站數據的人給了我json文件並離開了,所以我不知道如何獲取信息。我感謝您的幫助,並且您花時間回覆我的問題:D –

回答

1

內部元件陣列本身,你需要使用索引來訪問值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 
+0

非常感謝Alex!有用!!!!!!!!!!!我感謝你的幫助,比如大時間! –

+0

如果每個頂級數組中包含的元素更加一致,您可以通過執行foreach($ product as $ key => $ value)來使其更簡單一些。{print「$ key:$ value
」; }'在現有的'for'裏面......儘管這裏不能工作,因爲裏面有更多的嵌套數組。 –

+0

@AwahHammad你非常歡迎! –