2012-11-30 35 views
0

我有一個簡單的來自PHP的JSON StdClass對象,我希望將其格式化爲表/列表/ div,並消除過程中的其他鍵和值。該JSON看起來是這樣的:PHP或JQUERY 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); 
    } 
} 
+1

到底是什麼的問題進行檢查? –

+0

我剛剛更新了我到目前爲止所嘗試的代碼,感謝幫助 –

回答

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> 

哪裏$object是您json_decoded可變

編輯的名字: 增加了對空值過

+0

我無法實現它,我錯過了什麼? –

+0

我假設你正在創建一個類似'$ varname = json_decode($ whatever)的變量;'你需要把這個$ varname放入'get_object_vars($ object)'(改變$ object到你的變量)在我的例子中 – Dale

+0

我已經添加一個編輯,希望澄清 – Dale