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

时间:2016-02-25 14:26:54

标签: php html arrays json html-table

我有这个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和它们在一行中的平方英尺面积,第二层单元2A,2B以及它们在一行和第一层单元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>

这是预期的输出。 Output

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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:

<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

答案 2 :(得分:-1)

<div class="events">
  <div class="event event1 year1996 fact">
    <p>March,4,First edition of Financial News published,,fact,</p>
  </div>
  <div class="event event2 year1996 cover">
    <a href="images/covers/004_Square Mile.pdf" target="_blank">
      <img src="view-source:http://thetally.efinancialnews.com/tallyassets/20years/images/covers/004_Square%20Mile.jpg">
    </a>
    <p>March,25,,,cover,004_Square Mile</p>
  </div>
  <div class="event event3 year1997 fact">
    <p>April,5,Another on here to compare,no description,fact,</p>
  </div>
</div>

然后,您使用$json_string = "your json string like above"; //or you can $json_string = file_get_contents(url_return_your_json); 将其转换为数组

json_decode

答案 3 :(得分:-1)

问题似乎是你的JSON格式。您有 "trailing commas" 可以防止它被正确解码,从而在foreach循环中获得空结果。您有两种选择:

  1. 修复您的JSON并删除尾随逗号

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

    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);
    
  3. 一旦你这样做,你就可以用这种方式迭代来创建你的表:

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

答案 4 :(得分:-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