doormen2014 2013-10-08 05:34
浏览 11
已采纳

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

  • 写回答

2条回答 默认 最新

  • doumu9799 2013-10-08 06:04
    关注

    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);
      }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?