在将json数组解码为普通的php数组后,使用键获取图像url

时间:2017-06-19 08:08:12

标签: php arrays json

我真的不知道该怎么做。无法弄清楚。任何帮助都会很棒,拜托并谢谢。

JSON代码(它存储在数据库中tblproducts表的'images'列中)

{
"200x200":"http://img.fkcdn.com/image/mobile/p/s/u/lenovo-k6-power-k33a42-200x200-imaezt6hypjzhdug.jpeg",
"400x400":"http://img.fkcdn.com/image/mobile/p/s/u/lenovo-k6-power-k33a42-400x400-imaezt6hypjzhdug.jpeg",
"800x800":"http://img.fkcdn.com/image/mobile/p/s/u/lenovo-k6-power-k33a42-800x800-imaezt6hypjzhdug.jpeg",
"unknown":"http://img.fkcdn.com/image/mobile/p/s/u/lenovo-k6-power-k33a42-original-imaezt6hypjzhdug.jpeg"
}

我需要使用json_decode函数将json数组解码为普通的php数组,并使用键获取图像网址,获取每个图像并将其显示在不同的标记中。

<?php 
      $category_id = $_GET['category_id'];
      $result = mysql_query("select * from tblproducts where category_id = '$category_id");
      while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
          $json = $row['images'];
          $image = var_dump(json_decode($json, true));
      ?>
          <img src="<?php echo $image[0] ?>" alt=" " class="img-responsive" />
          <img src="<?php echo $image[1] ?>" alt=" " class="img-responsive" />
          <img src="<?php echo $image[2] ?>" alt=" " class="img-responsive" />
<?php } ?>

3 个答案:

答案 0 :(得分:0)

在此之后

$image = var_dump(json_decode($json, true));

DO

foreach($image as $key =>$val)
{?>
  <img src="<?php echo $val ?>" alt=" " class="img-responsive" />
<?php }

您需要在每个值

上使用foreach进行迭代

答案 1 :(得分:0)

试试这个:

$obj = json_decode($json, true);

echo $obj['unknown'];
// http://img.fkcdn.com/image/mobile/p/s/u/lenovo-k6-power-k33a42-original-imaezt6hypjzhdug.jpeg

Working Example

答案 2 :(得分:0)

更改您的PHP代码以迭代已获取的数组,并从代码中删除var_dump()

<?php 
    $category_id = $_GET['category_id'];
    $result = mysql_query("select * from tblproducts where category_id = '$category_id");
    while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
        $json = $row['images'];
        $image = json_decode($json, true);
        foreach($image as $key =>$val){
    ?>
        <img src="<?php echo $val ?>" alt=" " class="img-responsive" />
   <?php }
   }
?>