Reputation: 131
I am querying a database for results and trying to convert them into JSON encodable array where the key will act as the name of the pair and the value is the value. How would I do this in the following code below?
foreach($results as $result) {
foreach( $result as $key => $value ) {
if ($key == 'D')
{
$trimmed = round($value, 4);
}
else
{
$trimmed = trim($value, "\n\r");
}
$array[$i] ="$key"."=>"."$trimmed";
}
$i = 0;
$jret = json_encode($array);
echo $jret;
}
For example:
<?php
$object[0] = array("foo" => "bar", 12 => true);
$encoded_object = json_encode($object);
?>
output:
{"1": {"foo": "bar", "12": "true"}}
Upvotes: 0
Views: 674
Reputation: 157896
dunno what you need and why you mimic PHP code instead of using it, but may be
$array[] = array($key => $trimmed);
is what you are looking for
Upvotes: 1
Reputation: 14492
with
$array[$i][$key] = $trimmed;
you could do
$return = json_encode($object, JSON_FORCE_OBJECT);
at the end
Upvotes: 0