1

ajax calls below php and expect an array of json to be return. I think I have the data ready but don't know how to return them correctly.

$files = array();
foreach($db2_databaselist as $db) {

    $file = new stdClass();
    $file->data = date('Y-m-d--H:i:s',strtotime($db));
    $file->attr = new stdClass();
    $file->attr->rel = "file";
    $file->attr->timestamp = $db.$type[0];

    $files[] = json_encode($file);
}
   echo "<pre>Output = " . print_r($files,TRUE) . "</pre>";
   echo "<BR><BR><BR>";
   print_r($files, TRUE);

where print_r($files,TRUE) gives me

Output = Array
(
    [0] => {"data":"2011-08-07--02:30:05","attr":{"rel":"file","timestamp":"20110807023005w"}}
    [1] => {"data":"2011-07-31--02:30:09","attr":{"rel":"file","timestamp":"20110731023009w"}}
    [2] => {"data":"2011-07-24--02:30:09","attr":{"rel":"file","timestamp":"20110724023009w"}}
)

But print_r($files,TRUE) returns nothing.

How can I get php to return

[
 {"data":"2011-08-07--02:30:05","attr":{"rel":"file","timestamp":"20110807023005w"}},
 {"data":"2011-07-31--02:30:09","attr":{"rel":"file","timestamp":"20110731023009w"}},
    [2] => {"data":"2011-07-24--02:30:09","attr":{"rel":"file","timestamp":"20110724023009w"}}
]

3 Answers 3

2

You don't need json encode after the loop as things are. You need implode. Your array values are already JSON strings, which means that using json_encode will only escape the strings!

Instead:

echo '['.implode(',',$files).']';

OR! You could skip json_encode on this line:

$files[] = json_encode($file);

And the end of the loop would look like this instead:

    $files[] = $file;
}

$files = json_encode( $files );
Sign up to request clarification or add additional context in comments.

3 Comments

I like the second solution better. Great that you spotted it.
@Radek I didn't see the json_encode in the look first go round
I did it this way because I didn't know how to make $files an object so I can use objects only. So I made $files an array. Wors very smoothly now.
0

you need to use json_encode php function

print json_encode($files);

Comments

-1

echo json_encode($files) should be enough

Comments

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.