PHP中的JSON产品查看器[关闭]
I need to create a website that pulls data from a JSON API. The information is a product catalogue that contains the following array in JSON format.
[{
"id": "1",
"name": "Product Name",
"Description": "Lorem Ipsum"
},
{
"id": "2",
"name": "Product no 2"
"Description": "Lorem Ipsum"
}]
I've already successfully used curl to get the JSON and json_decode the data.
I need my website to have an index page that contains list of products (with just the name) that links to a more detail page that contains the description.
I need help on how to best approach this.
Thanks
我需要创建一个从JSON API中提取数据的网站。 该信息是一个产品目录,其中包含以下JSON格式的数组。 p>
[{
“id”:“1”,
“name”:“产品名称 “,
”描述“:”Lorem Ipsum“
},
{
”id“:”2“,
”名称“:”产品编号2“
”描述“:”Lorem Ipsum“
}]
code> pre>
我已经成功使用curl来获取JSON和json_decode数据。 p>
我需要我的网站有一个索引页面,其中包含链接到包含描述的更详细信息页面的产品列表(只有名称)。 p>
\ n
我需要有关如何最好地处理此问题的帮助。 p>
谢谢 p>
div>
From what I understand, you need index.php
do both jobs: act as a catalog and as a product presentation page.
The first thing you need to do is check if $_GET['product']
is set, in which case you should present the product, otherwise render a catalogue.
You could start by doing the following:
$cat=json_decode($retrieved_json);
if(!isset($_GET['product']))
{
// act as a catalog
$n=count($cat);
echo "<h3><em>$n</em> products:</h3>
<ul>";
foreach($cat as $product)
echo "<li><a href='?product={$product->id}'>{$product->name}</a></li>
";
echo "</ul>";
}
else
{
$product=$product_by_id($_GET['roduct']);
if($product)
{
// act as a product presentation, if the id exists
echo "<h3>{$product->name}</h3>
";
echo "<p>{$product->Description}</p>
";
echo "<p><em>Product id:<strong>{$product->id}</strong></em></p>
";
}
else
// display an error for non-existent ids
echo "<h2>No product with id={$_GET['roduct']} was found!</h2>";
}
// returns $cat's entry for the product $id
// or false if not found
function product_by_id($id)
{
global $cat;
for($i=0;($i<count($cat)))&&($cat[$i]->id!=$id));$i++) {}
return ($i<count($cat)?$cat[$i]:false);
}
Interesting. Most times you would use AJAX to get JSON data back from the server, I suppose you could do the same using curl. If you are able to assign the json string to a variable, you can simply json_decode it to create a php object.
Example:
$curl_response = getCurlData(); // Pretend this is your CURL retrieving function
$obj = json_decode($curl_response);
Then you can loop over the values in that object as you would any object, as such:
foreach ($obj as $data) {
echo '<a href="index.php?product=' . $data->id . '">Product</a>';
}