2

I am creating a json array in PHP like this (it's inside a class):

$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;

But I seem to get "strange" decodes the other end. I cannot actually reference the array by key's;

So far it will let me do this: (Where af_threads is the class name and $key id the ID in the table query)

$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;

But what it will not let me do is something like this

$threads[$key]['title']

I'm not sure why. As the class builds i.e. with more rows etc. I will need to call specific rows in specific places. i.e. $threads[$key]['newrow'], $threads[$key]['newrow2'], and or to manipulate a row with say substr(); etc.

Yes I know I could just echo out an array without json, but eventually I want to add cross domain functionality with JQuery getJSON() ...

Have I got it all wrong?

2
  • How does the generated JSON look like? Have you verified it is the same as you'd expect? Commented Feb 2, 2011 at 8:38
  • My json gives me something like this (1 & 2 are the tableID's $row->ID in the array creation): stdClass Object ( [1] => stdClass Object ( [title] => this is [content] => Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus interdum varius urna. Donec quis turpis elit. ) [2] => stdClass Object ( [title] => that is [content] => Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus interdum varius urna. Donec quis turpis elit. ) ) Commented Feb 2, 2011 at 8:42

1 Answer 1

3

By default, json_decode() returns stdClass, modify second line with

$threads = json_decode($threads->thread, true)

and you will get an associative array and be able to reference it by keys, $threads[$key]['title'] for example.

1
  • David - many many thanks, in the past I have always "serialized" and not played with json got it now with "true" Commented Feb 2, 2011 at 8:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.