Sunday 1 September 2013

PHP JSON foreach trouble

PHP JSON foreach trouble

I create a json structure with this php code:
<?php
include "../base.php";
$STH = $DBH->prepare("SELECT * FROM customers");
$STH->execute();
$result = $STH->fetchall(PDO::FETCH_ASSOC);
$rows = $STH->rowCount();
$jsontext = "{";
$jsontext .= "total: ".$rows.",";
$jsontext .= "page: 0,";
$jsontext .= "records: [";
foreach($result as $key => $inner_arr) {
$jsontext .= "{";
foreach($inner_arr as $field_name => $field_value) {
$jsontext .= "{$field_name}: {$field_value}, ";
}
$jsontext .= "},";
}
$jsontext .= "]";
$jsontext .= "}";
echo json_encode($jsontext);
?>
the main problem is this line $jsontext .= "{$field_name}: {$field_value}, ";
When I print the whole script with "echo" it works. But with $jsontext .=
it is not working and I receive only "null".

No comments:

Post a Comment