I need to send data to the client side in JSON format.
So far, it worked just fine with json_encode as follows:
$sql = "SELECT `card`.`CardID`,`card`.`Text`,... WHERE (`card`.`CardID`= :ItemId)";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':ItemId', $itemid);
$stmt->execute();
while ($row = $stmt->fetchObject()) {
$posts[]=$row;
}
...
...
$res["rows"] = $posts;
$res["maptel"] = $maptelindicator;
echo json_encode($res,JSON_UNESCAPED_UNICODE);
But now I have a problem. I have a new field (Videofiles) in the DB that is already JSON formatted- stored as the ouput of a SDK function. If I encode this JSON encoded field once more, I get data which is unreadable on the client side..
How can I json_encode all the other data, but skip this specific field, Videofiles?
Here is the output of a sample data structure using print_r:
Array
(
[rows] => Array
(
[0] => stdClass Object
(
[Name] => Company13
[CID] => 26
[CardID] => 26-000002
[Text] => Kleopatra Deluxe Hotel reservations
[ImageLink] =>
[VideoFiles] => [{"quality":"mobile","type":"video/mp4","width":480,"height":270....}]
[ClickDate] => 2015-11-03
)
)
[maptel] => 0
)
Thanks...
You could use json_decode to decode the already encoded field and then add the result in the $res array.
Best way to do it delete this section in SQL!
But if you want to delete in php it will have a cost for you and you can use unset for this situation;
foreach ($posts as $post){
unset($posts['VideoFiles']);
}
$res["rows"] = $posts;
$res["maptel"] = $maptelindicator;
echo json_encode($res,JSON_UNESCAPED_UNICODE);
Related
Array
(
[0] => Array
(
[acctcode] => 631
[description] => Blood Transfussion Set, Blood Transfusion Set- ADULT
[pchrgqty] => 1.00
[pchrgup] => 17.00
[pcchrgamt] => 17.00
[patlast] => GUADA�A
[patfirst] => FRITZIE ELINE
[patmiddle] => DAYTEC
[patsuffix] =>
)
)
The above array in php is result of print_r($result); now this array will be json_encoded as below:
echo json_encode($result, JSON_UNESCAPED_UNICODE);
I am encoding this because it is for ajax request. Now in echo part it is not returning anything. I dont know why this is happening but my guess is because of
“Ñ” which is in the [patlast] => GUADA�A and is shown as �. I am getting this result set in a select of MSSQL DATABASE.
How to handle this result set in MSSQL and be able to return the correct data.
I have found the best solution for my project in here
Using below code:
// Create an empty array for the encoded resultset
$rows = array();
// Loop over the db resultset and put encoded values into $rows
while($row = mysql_fetch_assoc($result)) {
$rows[] = array_map('utf8_encode', $row);
}
// Output $rows
echo json_encode($rows);
The answer was given my user Kemo
I have a site which I used JSON to save some data.
Here is how it saves data
{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}
Note: I know this is a poor way of doing it but I did it when I was not so vast!
The 1 is the user_id which changes according to the id of the user that takes an exam on the platform. The english, physics are the subjects this user took.
The maximum number of exam a user can take at a time is for so the json string will look like {"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"},"maths":{"grade":"7","time":"79"},"chemistry":{"grade":"3","time":"48"}}}
First I think this is the best way to save the result as a JSON string
[{"subject":"english","grade":"7","time":"79"}, {"subject":"physics", "grade":"3","time":"48"}}]
My problem is that I want to use PHP to work on the former on. I have done some few stripping of the string and I'm left with this {"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}
I tried this chunk
$JSONResult = json_decode($aScore->result);
foreach ($JSONResult as $subjectKey => $aSubject)
{
foreach ($aSubject as $theResult)
{
$userResult = '
Subject: **This is what I've not been able to get**
Grade: '.$theResult->grade.'
Time: '.$theResult->time.'
';
}
}
I tried $aSubject->subjectKey to get the associative key value from the first foreach statement but it did not work
Any help?
Added: Please leave comments about the way the JSON string was stored. I'd love to learn.
You don't need the inner loop. Each subject is just a single object, not an array. And the subject key is just $subjectKey, it's not a part of the object.
$JSONResult = json_decode($aScore->result, true); // to get an associative array rather than objects
foreach ($JSONResult as $subjectKey => $aSubject) {
$userResult = "
Subject: $subjectKey
Grade: {$aSubject['grade']}
Time: {$aSubject['time']}
";
}
DEMO
You could use the second argument to json_decode!
It changes your $JSONResult from stdClass to an associative Array!
Which means you can do something like this:
$str = '{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}';
$result = json_decode($str, true); // Put "true" in here!
echo "<pre>".print_r($result, true)."</pre>"; // Just for debugging!
Which would output this:
Array
(
[1] => Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
)
And in order to loop through it:
foreach ($result as $idx => $exams) {
echo $exams['english']['grade']."<br>";
echo $exams['physics']['grade']."<br>";
}
Which would output this:
7
3
Update
Without knowing the containing arrays data (Based on the example above)
$exams will be an Array (which could contain any sort of information):
Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
If you want to loop through $exams:
foreach ($result as $idx => $exams) {
foreach ($exams as $subject => $info) {
echo $info['grade']."<br>";
}
}
This would produce the same output as the above example, without needing to know a subject name!
Essentially, the data should look as follows, but as one array for each user that contains their info. It should be packaged as a JSON after completely looping through.
Preface
Using the pre tags with print_r I got what it should look like using some humorous sample data:
User 1 is following:
Array
(
[0] => Array
(
[first] => Hugh
[last] => Janus
[bg] => /resources/bg/2/b.png
[prof_pic] => /resources/profilepics/2/b.jpg
[bio] => 50% proctologist, 50% baker.
)
)
Array
(
[0] => Array
(
[first] => Andrew
[last] => Dickens
[bg] => /resources/bg/3.c.jpg
[prof_pic] => /resources/profilepics/3/c.jpeg
[bio] => Therapists are pretty cool.
)
)
Array
(
[0] => Array
(
[first] => Anita
[last] => Dickson
[bg] => /resources/bg/4/d.jpg
[prof_pic] => /resources/profilepics/4/d.JPG
[bio] => Just another barista.
)
)
Essentially, everything needs to come back as one JSON item that someone could use for any purpose with the supplied info.
Background on the Following Code
This code selects all User IDs from the table 'followers' where the person who is following someone is equal to fB and the person who owns that friendship is fA. In this instance, userID 1 is trying to look at a page of every person they follow with their profile pic, background pic, first name, last name, and bio. The data that the JSON is outputting will be formatted in another file, but this is just being used to curate the raw data.
$dbh is the PDO database connection and the code uses prepared statements for security.
Code
$flingJSON = 0;
$userid = "1";
$result = $dbh->prepare('SELECT fA
FROM followers
WHERE fB=:userid');
$result->bindParam(':userid', $userid);
$result->execute();
$rawData = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($rawData as $following) {
$followingID = $following['fA'];
$getInfoFling = $dbh->prepare('SELECT first, last, bg, prof_pic, bio
FROM users
WHERE id=:flingID
');
$getInfoFling->bindParam(':flingID', $followingID);
$getInfoFling->execute();
$flingJSON = $getInfoFling->fetchAll(PDO::FETCH_ASSOC);
echo "<pre>";
print_r($flingJSON);
echo "</pre>";
}
Your help is greatly appreciated in advance and as a thanks you'll get a shout-out in the documentation for this file.
This should return a single array with all the user's info:
//Create empty data array
$flingData = array();
$userid = "1";
$result = $dbh->prepare('SELECT fA
FROM followers
WHERE fB=:userid');
$result->bindParam(':userid', $userid);
$result->execute();
$rawData = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($rawData as $following) {
$followingID = $following['fA'];
$getInfoFling = $dbh->prepare('SELECT first, last, bg, prof_pic, bio
FROM users
WHERE id=:flingID
');
$getInfoFling->bindParam(':flingID', $followingID);
$getInfoFling->execute();
//Append user info to data array
$flingData[] = $getInfoFling->fetch(PDO::FETCH_ASSOC);
}
//Create JSON string
$flingJSON = json_encode($flingData);
echo "<pre>";
print_r($flingJSON);
echo "</pre>";
Here is the Json data stored in variable $json
[Data] => Array
(
[id_number] => Array
(
[value] => 123445567
[link] => 1234556
[class] =>
)
[date] => Array
(
[value] => 04-18-14
[link] => 1234556
[class] =>
)
Currently I access the lower levels like this:
foreach($json['Data'] as $data) {
foreach ($data['id_number'] as $id) {
print $id['value'];
}
}
There is only one result for id_number and only one result for date. Do I really need this second foreach loop? Isn't there a way to access it by just going to the lower level as an object so it would be something like
print $data->id_number->value
Thank you.
Since you have decoded the JSON string as an array you could do
foreach($json['Data'] as $data) {
print $data['id_number']['value'];
}
If you had decoded it into an object (don't set the second parameter to be true) then you could simply do it like you mentioned
foreach($json->Data as $data)
print $data->id_number->value;
Manual
You can retrieve the elements individually (without looping) by:
$id_number = $json['Data']['id_number']['value'];
$date = $json['Data']['date']['value'];
//etc ...
You can use:
$json['Data'][idnr]->value
If you know the id that is ofc, else you will have to loop
I have a table named listing_fees
and I want to get the data by the id of 12
the data that I want to get is a BLOB that is named [BLOB - 205B]
inside the BLOB file is an array like this:
a:7:{s:2:"id";s:1:"1";s:5:"label";s:8:"For Sale";s:6:"amount";s:4:"0.00";s:4:"days";s:1:"7";s:6:"images";s:1:"0";s:10:"categories";a:2:{s:3:"all";i:0;s:10:"categories";a:1:{i:0;i:30;}}s:10:"extra_data";N;}
I don't understand a thing on this code.
I want to display it on the frontend of my html using PHP
what will I to display it?
SQL Query or something else.
That data is in PHP Serialized format you can decode it using unserialize
Example
$data = 'a:7:{s:2:"id";s:1:"1";s:5:"label";s:8:"For Sale";s:6:"amount";s:4:"0.00";s:4:"days";s:1:"7";s:6:"images";s:1:"0";s:10:"categories";a:2:{s:3:"all";i:0;s:10:"categories";a:1:{i:0;i:30;}}s:10:"extra_data";N;}';
$data = unserialize($data);
echo "<pre>" ;
foreach ( $data as $key => $value ) {
if ($key == 'categories') {
echo $key, " = ", $value['categories']['0'], PHP_EOL;
} else {
echo $key, " = ", $value , PHP_EOL;
}
}
Output
id = 1
label = For Sale
amount = 0.00
days = 7
images = 0
categories = 30
extra_data =
The data in the BLOB column appears to be serialized data, not a file. Because of this, you don't want to just "output" it to the page - you'll want to unserialize it (via PHP's unserialize() method) and then process to be displayed, well, however it should be displayed. Taking the exact data you display in your question and passing using unserialize() on it gives me an array with the following:
Array
(
[id] => 1
[label] => For Sale
[amount] => 0.00
[days] => 7
[images] => 0
[categories] => Array
(
[all] => 0
[categories] => Array
(
[0] => 30
)
)
[extra_data] =>
)
A simple setup, to query the database and retrieve the column, would be:
$mysqli = new mysqli('localhost', 'username', 'password', 'db');
$result = $mysqli->query('SELECT column_name FROM listing_fees WHERE id = 12');
$data = $result->fetch_assoc();
$result->close();
To use the data that is in the $data array, you can do:
$blob = unserialize($data['column_name']);
Now, you can display the data however you want, accessing each value with $blob['label'] or $blob['days'].