php json数组问题

时间:2011-02-02 08:32:04

标签: php arrays json

我在PHP中创建一个json数组(它在类中):

$STH = $DBH->query("SELECT ID,title,content FROM table WHERE ID= '".$ID."' ");
$querycount = $STH->rowCount();
if($querycount!=0):
    $STH->setFetchMode(PDO::FETCH_OBJ); 
    while( $row = $STH->fetch()) :
        $thread[$row->ID]['title'] = $row->title;
        $thread[$row->ID]['content'] = $row->content;
    endwhile;
    $this->querycount = $querycount;
    $this->thread = json_encode($thread);
 else:
    $this->querycount = $querycount;
 endif;

但我似乎得到“奇怪”解码另一端。我实际上无法通过键引用数组;

到目前为止它会让我这样做:(其中af_threads是类名,$ key id是表查询中的ID)

$threads = new af_threads($key,$DBH);
$threads = json_decode($threads->thread); 
foreach($threads as $key1=>$thread): 
    foreach($thread as $key2=>$val):  
        echo $key2; 
        echo $val; 
    endforeach;
    echo '<hr />';
endforeach;

但它不会让我做的是这样的事情

$threads[$key]['title']

我不确定为什么。由于类构建即具有更多行等,我将需要在特定位置调用特定行。即$threads[$key]['newrow']$threads[$key]['newrow2']和/或操纵行substr();等

是的我知道我可以在没有json的情况下回显一个数组,但最终我想用JQuery getJSON()添加跨域功能......

我弄错了吗?

1 个答案:

答案 0 :(得分:3)

默认情况下,json_decode()会返回stdClass,请使用

修改第二行
$threads = json_decode($threads->thread, true)

您将获得一个关联数组,并且能够通过键引用它,例如$threads[$key]['title']

相关问题