0

我有一个来自 PHP 的简单 JSON StdClass 对象,我希望将其格式化为 table/list/div 并消除过程中的其他键和值。JSON 看起来像这样:

stdClass Object ( 
[msc] => 150 
[number] => 309 
[status] => OK 
[msc_mcc] => 652 
[imsi] => 652010154107728 
[mcc] => 652 
[operator_country] => Botswana 
[msc_operator_name] => MSC 
[msc_operator_country] => Botswana 
[msc_mnc] => 01 
[mnc] => 01 
[id] => 1072540715 
[msc_location] => 
[operator_name] => MSC )

我试过 PHP 并做了一个表格,但问题是我需要选择除整个身体以外的某些值,而且我还需要消除空值

function print_nice($elem,$max_level=10,$print_nice_stack=array()){ 
    if(is_array($elem) || is_object($elem)){ 
        if(in_array($elem,$print_nice_stack,true)){ 
            echo "<font color=red>RECURSION</font>"; 
            return; 
        } 
        $print_nice_stack[]=&$elem; 
        if($max_level<1){ 
            echo "<font color=red>nivel maximo alcanzado</font>"; 
            return; 
        } 
        $max_level--; 
        echo "<table class='table table-bordered table-striped'>"; 
        if(is_array($elem)){ 
            echo '<tr><th colspan=2><strong><font><h3>Results, with love</h3></font></strong></th></tr>'; 
        }else{ 
            echo '<tr><th colspan=2 class=hdrs><strong>'; 
            echo '<font color=white>OBJECT Type: '.get_class($elem).'</font></strong></th></tr>'; 
        } 
        $color=0; 
        foreach($elem as $k => $v){ 
            if($max_level%2){ 
                $rgb=($color++%2)?"#f5f5f5":"#efeeee"; 
            }else{ 
                $rgb=($color++%2)?"#f5f5f5":"#efeeee"; 
            } 
            echo '<tr><td valign="top" style="width:40px;background-color:'.$rgb.';">'; 
            echo '<strong>'.$k."</strong></td><td>"; 
            print_nice($v,$max_level,$print_nice_stack); 
            echo "</td></tr>"; 
        } 
        echo "</table>"; 
        return; 
    } 
    if($elem === null){ 
        echo "<font color=green>NULL</font>"; 
    }elseif($elem === 0){ 
        echo "0"; 
    }elseif($elem === true){ 
        echo "<font color=green>TRUE</font>"; 
    }elseif($elem === false){ 
        echo "<font color=green>FALSE</font>"; 
    }elseif($elem === ""){ 
        echo "<font color=green>EMPTY STRING</font>"; 
    }else{ 
        echo str_replace("\n","<strong><font color=red>*</font></strong><br>\n",$elem); 
    } 
} 
4

1 回答 1

0

get_object_vars()in_array()在这里可能会有所帮助

例如:

<?php
    $object = json_decode($jsonstring);
?>
<table>
    <?php
    foreach (get_object_vars($object) as $k => $v)
    {
        if (in_array($k, array('msc', 'number', 'status')) && ! empty($v))
        {
            echo '<tr>';
            echo "<td>{$k}</td><td>{$v}</td>";
            echo '</tr>';
        }
    }
    ?>
</table>

$objectjson_decoded 变量的名称在哪里

编辑:也添加了对空值的检查

于 2012-11-30T11:43:00.587 回答