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

4
我有这个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,
      }
   ]
}

我希望根据楼层号在表格中显示这些数据。例如,3楼的单元3A、3B和它们的面积总和在一行中显示,2楼的单元2A、2B和它们的面积总和在一行中显示,1楼的单元1A、1B和它们的面积总和在一行中显示。请帮忙。
我尝试了这个方法,但结果与预期不符。
$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>

以下是预期的输出结果: 输出

1
你尝试过什么吗?你尝试过的代码在哪里?你想让我们替你完成吗? - CodeGodie
感谢您包含您的代码。 - CodeGodie
1
json_decode的声明在哪里?我们需要看到您获取数据的方式以及如何将其提取到json_decode中,才能更好地了解您正在做什么。 - Sergio E. Diaz
1
你试过我的答案了吗?我认为这是最准确的答案,所需代码最短。如果它有效,请告诉我,我只是好奇。 - CodeGodie
它在@CodeGidie确实起作用了。非常感谢。在获取单元信息的调用之后,我还需要进行另一个REST调用。 - hemanth kumar
显示剩余2条评论
5个回答

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

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:

    $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>';

输出:

enter image description here


谢谢@mitkosoft,它作为一个单独的文件运行得很好。但是,通过REST调用获取到的JSON格式与我尝试将此代码与该JSON集成时得到的格式不同,导致出现错误,例如“array_flip()期望参数1为数组”,“尝试获取非对象属性”等等。 - hemanth kumar
只要给我们真正的JSON响应,而不是示例,就足够让我们提供正确的解决方案了。 - mitkosoft
这是我的真正问题,请看一下是否能解决。我已经提到了所有测试环境的URL和有效凭据。请帮助我。链接. - hemanth kumar
你在那里已经得到了我的答案。 - mitkosoft

0

这是另一种获取解决方案的方式:

<?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 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 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>

返回:

enter image description here


这段代码可以工作,但它不是动态的,因为你必须手动定义"$cells"。 - CodeGodie
@CodeGodie,我修好了。 - miglio
谢谢@miglio,它作为一个单独的文件运行正常。但是,通过REST调用获取到的JSON格式与此代码集成时不同,我遇到了一些错误,例如“array_flip()期望参数1为数组”,“尝试获取非对象属性”,“foreach()提供的参数无效”等等。 - hemanth kumar
@hemanthkumar,你试过我的答案了吗?我确信它会起作用的。 - CodeGodie

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

然后,您可以使用json_decode将其转换为数组

$your_array = json_decode($json_string,1);

@CodeGodie:有一大堆代码,几百行那么多。所以我只添加了必要的代码。如果不清楚的话,请见谅。 - hemanth kumar
@hemanthkumar 没问题。只需确保包括与问题相关的任何区域,以便我们更好地解决问题。无论如何,就像我在上面的评论中所说,问题在于您的JSON格式。 - CodeGodie

-1
问题似乎出在您的JSON格式上。您有一个"尾随逗号",它会阻止其正确解码,从而导致foreach循环中得到空结果。您有两个选择:
  1. 修复你的 JSON 并删除尾随逗号:

    {
        "next_offset": -1,
        "records":    [
                {
                   "id": "87dad127-a60e-15a3-148e-56c7675f11df",
                   "name": "1A Unit",
                   "suite": "1A",
                   "sf": 1200,
                   "unit_floor": 1
                }
         ]
    } 
    
  2. 使用一个函数 (source) 在运行 json_decode 前自动删除这些逗号:

    function removeTrailingCommas($json)
    {
        $json = preg_replace('/,\s*([\]}])/m', '$1', $json);
        return $json;
    }
    
    $json = ''; // <-- 你的原始 JSON 字符串
    
    $json = removeTrailingCommas($json);
    $unit_json = json_decode($json, 1);
    

完成这一步后,您可以按照这种方式进行迭代,以创建您的表格:

$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>

可以请投反对票的人解释一下为什么要反对吗?也许你能教我一些我忽略的东西。谢谢。 - CodeGodie

-2

在PHP中实现这一点,使用read()从某个地方加载文件,然后在其内容中执行json_decode(),有效地创建一个数组,然后使用foreach循环遍历每个元素,使用模板来显示值。还要记得传递第二个参数,因为它会创建一个关联数组而不是对象。

$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...
}

这只是一个大致的想法,但应该能帮助你入门。

更完整的想法可以举个例子,

<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>

编辑:我看到你的错误了,你正在将一个键传递给foreach循环,但是foreach循环需要数组作为输入,除非数组在键内。如果是这样,我需要看到你解码和转储的位置。

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

这里是参数实例: https://eval.in/525451


我同意这个答案,但是原帖作者应该在给出任何答案之前提供一些他/她尝试过的代码。 - CodeGodie
他们现在更新了他们的问题并提供了代码。不错。 - CodeGodie
更新:请注意,如果要点踩,请解释原因。这是规定。 - Sergio E. Diaz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接