在HTML中的foreach循环php中反转一个json对象 [英] reverse a json object in foreach loop php in the html

查看:67
本文介绍了在HTML中的foreach循环php中反转一个json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试反转数组,以便将json对象的内容反转显示在前端.

I am trying to reverse an array so that the content of a json object will be rendered on the front end in reverse.

我正在使用reverse_array()功能,例如foreach(array_reverse($json) as $obj){....,但是,当我使用此功能时,页面空白.当我使用foreach($json as $obj){...时,一切正常.

I am using the reverse_array() function, like this foreach(array_reverse($json) as $obj){.... however, when I use this the page is blank. when I use foreach($json as $obj){... everything works.

我的json对象看起来像这样

My json object looks like this

{
    "1.49514754373E+12": {
        "description": "This is the first post in the json obj but i want it to be second in my html",
        "fileNames": [
            "3.jpg"
        ],

    },

    "1.71284754373E+12": {
        "description": "This is the second post in the json obj but i want it to be first in my html",
        "fileNames": [
            "1.jpg"
        ],

    },

}

我的代码如下

  <?php
    $json = file_get_contents('auction.json');
    $json = json_decode($json);

    foreach(array_reverse($json) as $obj){

     if(isset($obj->description) && $obj->description != ''){

      echo "<div class='row auction-item'>";

        echo "<p>" .$obj->description . "</p>";

        for ($x=0; $x < count($obj->fileNames); $x++) {

          echo "<div class='col-1-3' style=\"background-image: url('" . "/images/" . $obj->fileNames[$x] . "');background-size: cover; background-repeat: no-repeat; background-position: center; height: 100%;\"></div>";

        }

      echo "</div>";
     }
    }
    ?>

推荐答案

json_decode()默认情况下返回一个对象,而不是一个数组.

json_decode() returns an object by default, not an array.

尝试使用json_decode($json, true);强制其返回数组:

Try json_decode($json, true); to force it to return an array:

$json = file_get_contents('auction.json');
$json = json_decode($json, true);

foreach(array_reverse($json) as $obj){
    // note that your nested objects are now also arrays, so you'll need
    // to change the way you read from them
    if(isset($obj['description']) && $obj['description'] != ''){
        echo "<div class='row auction-item'>";
        echo "<p>" . $obj['description'] . "</p>";

        for ($x=0; $x < count($obj['fileNames']); $x++) {
            echo "<div class='col-1-3' style=\"background-image: url('" . "/images/" . $obj['fileNames'][$x] . "');background-size: cover; background-repeat: no-repeat; background-position: center; height: 100%;\"></div>";
        }

        echo "</div>";
    }
}

这篇关于在HTML中的foreach循环php中反转一个json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆