我想检索json_decode数据。如何在这里写foreach

时间:2015-02-18 14:37:48

标签: php

$classconducted = json_encode(array('segment'=>$segment,'Board'=>$board,'classFiveSubject'=>$subject5,'classeightboard'=>$eightboard,'classeightsubject'=>$subject8,'classTenthboard'=>$tenthboard,'classTenthsubject'=>$subject8,'engineering'=>$engineering));

$ in ='{“segment”:[“IV级学费”,“VI-VIII级学费”,“IX-X级学费”],“委员会”:[“cbse”,“cse / Ise” , “国家”], “classFiveSubject”: “allsubject”, “科学”], “classeightboard”: “CBSE”, “CSE /伊势”], “classeightsubject”:空, “classTenthboard”: “CBSE” “CSE /伊势”], “classTenthsubject”:NULL, “工程”:NULL}“;         print_r(json_decode($ in));

MyOutput中:

stdClass Object
(
    [segment] => Array
        (
            [0] => Class I-V Tuition
            [1] => Class VI-VIII Tuition
            [2] => Class IX-X Tuition
        )

    [Board] => Array
        (
            [0] => cbse
            [1] => cse/Ise
            [2] => State
        )

    [classFiveSubject] => Array
        (
            [0] => allsubject
            [1] => science
        )

    [classeightboard] => Array
        (
            [0] => cbse
            [1] => cse/Ise
        )

    [classeightsubject] =>
    [classTenthboard] => Array
        (
            [0] => cbse
            [1] => cse/Ise
        )

    [classTenthsubject] =>
    [engineering] =>
)

I have used the following code to retrieve the data. but I could not workout it.can any one guide me how to solve this?
       <?php
$sql=mysql_query("select * from tinfo");
while($row=mysql_fetch_array($sql))
{
$in=$row['classconducted'];
}
echo "<pre>";
$value=json_decode($in, true);//echo count($in); exit;
foreach ($value as $k => $val)    
{
echo "$k | $val <br />";
} 
?>

输出是:这里是列出索引键,值不是如何在这里使用foreach。我想检索键和值。

segment | Array 
Board | Array 
classFiveSubject | Array 
classeightboard | Array 
classeightsubject | Array 
classTenthboard |  
classTenthsubject | Array 
engineering | Array 

I want the  output form my json_decode  like this:
segment:Class I-V Tuition
Board:CBSE,STATE
classFiveSubject:AllSubject,Maths,Science
segment:Class VI-VIII Tuition
Board:CBSE, STATE
classEightSUbject:AllSubject,Maths,Science 

任何人都可以给我正确的代码吗?列出json_decode数据的方法是什么。

2 个答案:

答案 0 :(得分:0)

未经测试,但请尝试:

foreach (json_decode($in, true) as $key => $val) {

  echo $key.': ';
  if (is_array($val))
    echo implode(',', $val) . "\n";
  else
    echo $val . "\n";
  
}

答案 1 :(得分:0)

define('BR', '<br />');

$json = json_decode($in, true);

foreach ($json as $key => $arr ) {
    echo $key.BR;

    foreach( $arr as $value ) {
        echo $value.BR; 
    }

}