Reputation: 1255
I have a MySQL query in PHP that pulls back two columns of results
Column One is Label Column Two is Value
I have read http://nitschinger.at/Handling-JSON-like-a-boss-in-PHP but im struggling to understand how I can do the following JSON in PHP from MySQL
[
{
key: "Cumulative Return",
values: [
{
"label": "One",
"value" : 29.765957771107
} ,
{
"label": "Two",
"value" : 0
} ,
{
"label": "Three",
"value" : 32.807804682612
} ,
{
"label": "Four",
"value" : 196.45946739256
} ,
{
"label": "Five",
"value" : 0.19434030906893
} ,
{
"label": "Six",
"value" : 98.079782601442
} ,
{
"label": "Seven",
"value" : 13.925743130903
} ,
{
"label": "Eight",
"value" : 5.1387322875705
}
]
}
]
I can manually write a loop to output the raw text to form a JSON like above but I really want to use json_encode
<?php
$hostname = 'localhost'; //MySQL database
$username = 'root'; //MySQL user
$password = ''; //MySQL Password
try {
$dbh = new PDO("mysql:host=$hostname;dbname=etl", $username, $password);
$query = "select label, value from table";
$stmt = $dbh->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!empty($result)) {
echo '[
{
key: "Cumulative Return",
values: [';
for ($row = 0; $row < count($result); $row++) {
echo "{";
echo '"label": "' . $result[$row]['Label'] . '",';
echo '"Value": ' . $result[$row]['Value'];
echo "},";
echo ' ]
}
]';
}
}
}
catch (PDOException $e) {
echo $e->getMessage();
}
?>
Can this be done? if so how?
Upvotes: 2
Views: 5090
Reputation: 69
I build a simple function (I prefer to use it then json_encode - because I have full control of the fetched data):
public function mysqlToJoson($mysqlarray)
{
$json_string = "[";
while ($array = $mysqlarray->fetch()) {
$i = 1;
if ($json_string != "["){$json_string .= ",";}
foreach ($array as $key => $value) {
if ($i == 1) {
$json_string .= '{"' . $key . '":' . '"' . htmlentities($value,ENT_QUOTES, 'UTF-8') . '"';
} else $json_string .= ',"' . $key . '":' . '"' . htmlentities($value,ENT_QUOTES, 'UTF-8') . '"';
$i++;
}
$json_string .= '}';
}
$json_string .= ']';
return $json_string;
}
Upvotes: 0
Reputation: 2747
Iam using code igniter
this is how i created custom json from the values from the data base hope it helps
function getData() {
$query = $this -> db -> get('gcm_users');
$result_array=array();
if ($query -> num_rows() > 0) {
$results=$query->result();
foreach ( $results as $row) {
$data=array();
$data['name']=$row->name;
$data['email']=$row->email;
array_push($result_array,$data) ;
}
return json_encode($result_array);
} else {
echo "something went wrong";
}
}
this my function for retriving data from db since im using a frame work such as Code igniter i dont have to worry about my other sql operation hope you can extract what you need from this code..
output is like this
[{"name":"allu","email":"[email protected]"},{"name":"ameeen","email":"[email protected]"}]
Upvotes: 0
Reputation: 2409
Try this:
$hostname = 'localhost'; //MySQL database
$username = 'root'; //MySQL user
$password = ''; //MySQL Password
try {
$dbh = new PDO("mysql:host=$hostname;dbname=etl", $username, $password);
$query = "select label, value from table";
$stmt = $dbh->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$values = array();
for($row = 0; $row < count($result); $row++)
{
$values[] = array('label' => $result[$row]['Label'], 'value' => $result[$row]['Value']);
}
$to_encode = array(
array('key' => 'Cumulative Return',
'values' => $values;
)
);
echo json_encode($to_encode);
} catch (PDOException $e) {
echo $e->getMessage();
}
Upvotes: 3
Reputation:
Use json_encode()
$jsonArr = array( 'key' => 'Cumulative Return' , 'values' => array() );
foreach ($result as $res)
{
$jsonArr['values'][] = array('label'=>$res['Label'],'value'=>$res['value']);
}
echo json_encode($jsonArr);
Upvotes: 4
Reputation: 9930
That's the usefulness of JSON - that you don't need to bother to encode it manually.
$json = array();
$results = array();
$json['key'] = 'Cumulative return';
foreach ($row as $entry) {
$results['label'] = $entry['Label'];
$results['value'] = $entry['Value'];
$json['value'][] = $results;
}
echo json_encode($json);
And that's it. Enjoy!
Upvotes: 1
Reputation: 3806
You just need to create the array in the way you want it to be converted to json:
$encode = array(
'key' => 'Cumulative Return',
'values' => $result->fetchAll(PDO::FETCH_ASSOC)
);
echo json_encode($encode);
This should be what you are asking for.
Upvotes: 2