简体   繁体   English

无法将JSON解码为PHP数组并显示在HTML表中

[英]Unable to decode JSON into PHP array and display in HTML table

I have this json data 我有这个json数据

{
   "next_offset": -1,
   "records":    [
            {
         "id": "87dad127-a60e-15a3-148e-56c7675f11df",
         "name": "1A Unit",
         "suite": "1A",
         "sf": 1200,
         "unit_floor": 1,
      },
            {
         "id": "f386a7ad-d6ea-6eb1-9b8f-56cd6104c445",
         "name": "3B Unit",
         "suite": "3B",
         "sf": 450,
         "unit_floor": 3,
      },
            {
         "id": "b352dc84-8c76-6c27-daa4-56cd61e71aa2",
         "name": "3A Unit",
         "suite": "3A",
         "sf": 450,
         "unit_floor": 3,
      },
            {
         "id": "8ec4325a-1271-560e-888b-56cd6120f5de",
         "name": "2B Unit",
         "suite": "2B",
         "sf": 450,
         "unit_floor": 2,
      },
            {
         "id": "5a15fd5e-246a-be4b-fd5d-56cd619e9ee1",
         "name": "1B Unit",
         "suite": "1B",
         "sf": 450,
         "unit_floor": 1,
      },
            {
         "id": "61a55092-5683-1088-2d6c-56c99c5d4873",
         "name": "2A Unit",
         "suite": "2A",
         "sf": 3000,
         "unit_floor": 2,
      }
   ]
}

I want to display this data in table depending on the floor number,. 我想根据楼层号在表格中显示此数据。 Like 3rd floor units 3A, 3B and total of their area in sqft in one row, 2nd floor units 2A, 2B and their sum of area in one row and 1st floor units 1A, 1B and their area sum in one row. 类似于第三层单元3A,3B及其总面积以平方英尺为单位,第二层单元2A,2B及其面积为一排的总和以及第一层单元1A,1B及其面积为一排的总和。 Please help me. 请帮我。

I tried this but its not giving the expected result 我尝试了这个,但是没有给出预期的结果

$unit_response = call($url, $oauth2_token_response->access_token, 'GET');

        $unit_json = json_decode(json_encode($unit_response),true);
    <table class="stak-plan">

                <?php foreach ($unit_json['records'] as $unit_data) { ?>

                <tr>
                    <td>Floor: 3</td>
                    <td> 
                        Suit : <?php echo $unit_data['name'] ?><br>
                        SF : <?php echo $unit_data['sf'] ?>
                    </td>
                    <td>Suite: 3B<br /> SF: 25,000</td>
                    <td>Suite: 3C<br /> SF: 25,000</td>
                    <td> 
                    </td>
                </tr>  
                <?php } ?>

                </table>

Here is the expected output,. 这是预期的输出。 输出量

CSS: CSS:

<style>
    td{
        border: 1px solid black;
        padding: 15px;
    }
</style>

JSON (some extra commas has been removed): JSON(一些多余的逗号已被删除):

$json = '{
    "next_offset": -1,
    "records":    [
             {
          "id": "87dad127-a60e-15a3-148e-56c7675f11df",
          "name": "1A Unit",
          "suite": "1A",
          "sf": 1200,
          "unit_floor": 1
       },
             {
          "id": "f386a7ad-d6ea-6eb1-9b8f-56cd6104c445",
          "name": "3B Unit",
          "suite": "3B",
          "sf": 450,
          "unit_floor": 3
       },
             {
          "id": "b352dc84-8c76-6c27-daa4-56cd61e71aa2",
          "name": "3A Unit",
          "suite": "3A",
          "sf": 450,
          "unit_floor": 3
       },
             {
          "id": "8ec4325a-1271-560e-888b-56cd6120f5de",
          "name": "2B Unit",
          "suite": "2B",
          "sf": 450,
          "unit_floor": 2
       },
             {
          "id": "5a15fd5e-246a-be4b-fd5d-56cd619e9ee1",
          "name": "1B Unit",
          "suite": "1B",
          "sf": 450,
          "unit_floor": 1
       },
             {
          "id": "61a55092-5683-1088-2d6c-56c99c5d4873",
          "name": "2A Unit",
          "suite": "2A",
          "sf": 3000,
          "unit_floor": 2
       }
    ]
 }';

PHP: PHP:

    $jd = json_decode($json);
    $floors = array();
    foreach ($jd->records AS $key => $obj) {
        $f = $obj->unit_floor;
        $id = $obj->id;
        $name = $obj->name;
        $suite = $obj->suite;
        $sf = $obj->sf;
        $floors[$f][$suite]['name'] = $name;
        $floors[$f][$suite]['id'] = $id;
        $floors[$f][$suite]['sf'] = $sf;
    }
    //sort floors in desc order
    krsort($floors);
    foreach($floors as $id => $floor){
        ksort($floors[$id]);
    }
    print '<table>';
    foreach($floors as $floor => $suites){
        $sqf = 0;
        print '<tr>';
            print '<td>FLOOR: '.$floor.'</td>';
            foreach($suites AS $suite => $value){
                $sqf += $value['sf'];
                print '<td>Suite: '.$suite.'<br>SF: '.$value['sf'].'</td>';
            }
            print '<td>'.$sqf.'</td>';
        print '</tr>';
    }
    print '</table>';

OUTPUT: 输出:

在此处输入图片说明

this is other way to get the solution : 这是获得解决方案的另一种方法:

<?php
$json = '{
   "next_offset": -1,
   "records":    [
            {
         "id": "87dad127-a60e-15a3-148e-56c7675f11df",
         "name": "1A Unit",
         "suite": "1A",
         "sf": 1200,
         "unit_floor": 1
      },
            {
         "id": "f386a7ad-d6ea-6eb1-9b8f-56cd6104c445",
         "name": "3B Unit",
         "suite": "3B",
         "sf": 450,
         "unit_floor": 3
      },
            {
         "id": "b352dc84-8c76-6c27-daa4-56cd61e71aa2",
         "name": "3A Unit",
         "suite": "3A",
         "sf": 450,
         "unit_floor": 3
      },
            {
         "id": "8ec4325a-1271-560e-888b-56cd6120f5de",
         "name": "2B Unit",
         "suite": "2B",
         "sf": 450,
         "unit_floor": 2
      },
            {
         "id": "5a15fd5e-246a-be4b-fd5d-56cd619e9ee1",
         "name": "1B Unit",
         "suite": "1B",
         "sf": 450,
         "unit_floor": 1
      },
            {
         "id": "61a55092-5683-1088-2d6c-56c99c5d4873",
         "name": "2A Unit",
         "suite": "2A",
         "sf": 3000,
         "unit_floor": 2
      }
   ]
}';

function to parse data: 解析数据的功能:

function createArray($unit_json){
    $max_unit_floor = 0;
    $subcells=array_map(function($n)use(&$max_unit_floor){
        if((int)$max_unit_floor < (int)$n->unit_floor){ $max_unit_floor = $n->unit_floor; }
        return preg_replace('/\d*/','',$n->suite);
    },$unit_json->records);
    $subcells = array_flip(array_flip($subcells));
    $cells = array();
    for($i = $max_unit_floor; $i > 0; $i--){
        $values = array();
        foreach($subcells as $v){
            $values[] = $i.$v;
        }
        $cells['floor_'.$i] = array('title'=>'Floor: '.$i,'values'=>$values,"total"=>0);
    }
    foreach ($unit_json->records as $unit_data){
        foreach ($cells as $key=>$value){
            for($i=0;$i<count($value['values']);$i++)
            if($value['values'][$i]==$unit_data->suite){
                $cells[$key][$value['values'][$i]] = array("sf"=>$unit_data->sf);
                $cells[$key]["total"] += (float)$unit_data->sf;
            }
        }
    }
    return $cells;
}
?>

html table: html表格:

<table class="stak-plan" border="1" cellpadding="4" cellspacing="0">
<?php 
$unit_json = json_decode($json);
$cells = createArray($unit_json);
foreach ($cells as $key=>$value) { 
?>
<tr>
    <td><?php echo $value['title']?></td>
    <?php foreach($value['values'] as $k=>$cell){ ?>
        <td>Suite: <?php echo $cell?><br /> SF: <?php echo isset($cells[$key][$cell]['sf'])?$cells[$key][$cell]['sf']:''; ?></td>
    <?php }?>
    <td>sum: <?php echo $cells[$key]["total"]; ?></td>
</tr>  
<?php } ?>
</table>

response: 响应:

在此处输入图片说明

$json_string = "your json string like above";
//or you can $json_string = file_get_contents(url_return_your_json);

Then, you using json_decode for convert it to array 然后,您使用json_decode将其转换为数组

$your_array = json_decode($json_string,1);

The problem seems to be your JSON format. 问题似乎是您的JSON格式。 You have "trailing commas" that will prevent it from being decoded properly, and thus, getting empty results in your foreach loop. 您有“尾随逗号” ,这将阻止其正确解码,从而在您的foreach循环中得到空结果。 You have two options: 您有两种选择:

  1. fix your JSON and remove the trailing commas 修复JSON并删除结尾的逗号

     { "next_offset": -1, "records": [ { "id": "87dad127-a60e-15a3-148e-56c7675f11df", "name": "1A Unit", "suite": "1A", "sf": 1200, "unit_floor": 1, // <-- TRAILING COMMA } ] } 
  2. Use a function ( source ) that automatically removes these commas before you run your json_decode : 在运行json_decode之前,请使用自动删除这些逗号的函数( ):

     function removeTrailingCommas($json) { $json = preg_replace('/,\\s*([\\]}])/m', '$1', $json); return $json; } $json = ''; // <-- your ogiginal JSON string $json = removeTrailingCommas($json); $unit_json = json_decode($json, 1); 

Once you do that, you can then iterate in this manner to create your table: 完成此操作后,就可以用这种方式进行迭代以创建表:

$floors = array();
foreach ($unit_json['records'] as $record) {
    $floors[$record['unit_floor']][$record['suite']] = $record;
}
krsort($floors);
?>

<table class="stak-plan">
    <?php foreach ($floors as $floor_num => $floor_units) { ?>
        <tr>
            <td>Floor: <?= $floor_num ?></td>
            <?php
            ksort($floor_units);
            foreach ($floor_units as $unit) {
                ?>
                <td>
                    Suite : <?= $unit['suite'] ?><br>
                    SF : <?= $unit['sf'] ?>
                </td>
                <?php
            }
            ?>
            <td>
                <?php
                echo array_sum(array_map(function ($item) {
                    return $item['sf'];
                }, $floor_units));
                ?>
            </td>
        </tr>
    <?php } ?>
</table>

To achieve this in PHP, load the file from somewhere using read() and then execute json_decode() in its contents, effectively creating an array, then use a foreach loop to iterate through each, using a template to display the values. 要在PHP中实现此目的,请使用read()从某处加载文件,然后在其内容中执行json_decode() ,有效地创建一个数组,然后使用foreach循环遍历每个文件,并使用模板显示值。 Also remember to pass the second argument as it creates an associative array instead of an object. 还请记住传递第二个参数,因为它创建了关联数组而不是对象。

$contents = //open file from fs or wherever you want to get it (curl, etc)
$array = json_decode($contents, 1); //argument for assoc array
foreach ($array as $key => $value) {
   // echo your table...
}

This is a rough idea of how to do it, but should get you on your way. 这是一个大概的想法,但是应该可以帮助您。

A more complete idea would be for example, 例如,一个更完整的想法是

<table>
  <?php foreach ($array as $key => $val): ?>
    <!-- your table arrangement in html -->
    <?= $key ?>
    <?php // do whatever you want here with the array... ?>
    <?= $value ?>
  <?php endforeach; ?>
</table>

EDIT: I see your error, you're passing a key to a foreach loop but foreach loops take arrays as input, unless the array is inside the key. 编辑:我看到您的错误,您正在将密钥传递给foreach循环,但是foreach循环将数组作为输入,除非数组在键内部。 If so, I'd need to see where you're decoding and where you're dumping it. 如果是这样,我需要查看您在哪里解码以及在哪里转储它。

Read more about json_decode here: http://php.net/manual/en/function.json-decode.php 在此处阅读有关json_decode的更多信息: http ://php.net/manual/zh/function.json-decode.php

And here is an example of the argument in action: https://eval.in/525451 这是一个实际参数的示例: https : //eval.in/525451

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM