如何根据键和值限制行和拆分表? - PHP& JSON

时间:2016-09-09 04:56:12

标签: php json

如果找到超过10行,我试图将表限制为10行,创建一个新表。数据从JSON读取。代码看起来像这样:

System.InvalidOperationException

所需的输出如下所示:

<?php

$json = '{"test1": {
        "sub1": [
            "1", "2", "3"
        ],
        "sub2": [
            "1", "2", "3","4"
        ],
        "sub3": [
            "1", "2", "3","4"
        ],
        "sub4": [
            "1", "2"
        ]
    }
  }';

$results = json_decode($json);

echo '<table>';
foreach ($results->test1 as $key => $jsons) {

    foreach ($jsons as $value) {
        echo '<tr>';
        echo '<td>'.ucwords($key).'</td>';
        echo '<td>' . $value . '</td>';
        echo '</tr>';

    }
}
echo '</table>';
?>

我使用<table> <tr> <td>Sub1</td> <td>1</td> </tr> <tr> <td></td> <td>2</td> </tr> <tr> <td></td> <td>3</td> </tr> <tr> <td>Sub2</td> <td>1</td> </tr> <tr> <td></td> <td>2</td> </tr> <tr> <td></td> <td>3</td> </tr> <tr> <td></td> <td>4</td> </tr> <tr> <td>Sub3</td> <td>1</td> </tr> <tr> <td></td> <td>2</td> </tr> <tr> <td></td> <td>3</td> </tr> </table> <table> <tr> <td>Sub3</td> <td>4</td> </tr> <tr> <td>Sub4</td> <td>1</td> </tr> <tr> <td></td> <td>2</td> </tr> </table> 循环我是否必须使用foreach循环来计算JSON文件的大小并将其限制为10然后继续?

或者有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

一种方法是在标志上使用布尔标头。然后使用modulo % 10 == 0来剪切它。下面是使用它创建一个新的批处理。

$results = json_decode($json);
$new_array = array();
$i = 0;
foreach($results->test1 as $k => $value) {
    $header = true;
    foreach($value as $k2 => $v) {
        if($i % 10 == 0 || $header) {
            $key_pair = array($k, $v);
        } else {
            $key_pair = array(null, $v);
        }
        $i++;
        $new_array[] = $key_pair;
        $header = false;
    }
}

foreach(array_chunk($new_array, 10) as $value) {
echo '<table>'; 
    foreach($value as $tr) {
        echo '<tr><td>', implode('</td><td>', $tr), '</td></tr>';
    }
echo '</table>';