「php入門」file_get_contents()でjsonデータを取得するサンプル

1.item.json
{
“goods”:[
{
“type”:1,
“name”:”data1″,
“product”:[
{
“id”:88,
“name”:”data2″,
“title”:” title122″,
“titleDesc”:”gg11,gg12″,
“price”:1234.00
},
{
“id”:89,
“name”:”test78″,
“title”:”data6 title13 title14″,
“titleDesc”:”desc12,desc44″,
“price”:3211.00
}
]
},
{
“type”:2,
“name”:”data5″,
“product”:[]
}
]

}
2.phpコード
<?php
$type = $_GET[‘type’];
$proId = $_GET[‘id’];
echo $type.”item type”;
echo $proId.”item Id”;
$json_string = file_get_contents(‘json/item.json’);

//JSON文字列を配列に変換
$data = json_decode($json_string, true);

//商品
function itemForeach($d,$type,$proId)
{
foreach ($d[“goods”] as $key => $value) {
if($value[“type”] == $type){
$results = $value;
}
}
foreach ($results[“product”] as $key => $value) {
if($value[“id”] == $proId){
$result = $value;
}
}
return $result;
}
$res = itemForeach($data,$type,$proId);
print_r($res);
?>

Comments are closed.