I am storing a JSON array of data within a row in a database and attempting to retrieve the array in order to use in a foreach loop.
The code below is the code that I will be using for the foreach loop, but I am having some troubles actually retrieving the data, using PDO, as needed to be used.
$data = '[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]';
$array = json_decode($data, true);
foreach($array as $data){
echo $data['id'];
}
The problem I am having is retrieving the array to put into $data using PDO. Currently I have this query and code, the output for which is below.
$statement = $this->db_connection->prepare("SELECT gp FROM gs WHERE c_s= :c_s");
$statement->bindParam(':c_s', $c_s);
$statement->execute();
$data = $statement->fetchAll();
$result = json_encode($data, true);
return $result;
Mixed with the following code to show the array:
foreach ($result as $key) {
echo $key['id'];
}
print_r($result);
die();
This gives an error for the for each, and outputs the array (unusable) as following:
[{"gp":"[{\"id\":\"H592736029375\"},{\"id\":\"K235098273598\"},{\"id\":\"B039571208517\"}]","0":"[{\"id\":\"H592736029375\"},{\"id\":\"K235098273598\"},{\"id\":\"B039571208517\"}]"}]
Being as the first segment of code I have I can use the data as I needed I'm just in need of some guidance of how to correctly get the array from the database to then be used in the foreach.
I'm aware that I'm currently using json_encode instead of json_decode, using json_decode gives the following error:
Warning: json_decode() expects parameter 1 to be string, array given
Suggestions for my errors would be much appreciated
fetchAll() returns an array of rows, not the single field you expect:
$statement = $this->db_connection->prepare("SELECT gp FROM gs WHERE c_s= :c_s");
$statement->bindParam(':c_s', $c_s);
$statement->execute();
$rows = $statement->fetchAll();
$data = $rows[0]['gp'];
$result = json_decode($data);
You are expecting $data to be a string while it's an array. Either use $statement->fetchColumn() to retreive a single field or use json_decode($data['gp'])
Other then that, I'm not exactly sure why you are looping over a json_encoded array, you can't do that.
json_encode() formats variables for javascript object notation.
json_decode() loads variables from strings(READ: string, not array) in the javascript object notation.
To make it even clearer:
use json_encode() to insert data in mysql.
use json_decode() to put back a column to their corresponding php variable/state.
Related
Im not sure what is happening, but if i do
json_encode()
On a single array, i get valid json, but if i do something like
$ar['key'] = "name";
$array[] = json_encode($ar);
$json = json_encode($array);
It will return invalid json like so:
["{"key":"name"}"]
The expected outcome is
[{"key":"name"}]
I have searched for hours trying to find what is going on.
Due to lack of desired outcome, I can only assume you are trying to get a multidimensional array.
The correct way to achieve this would be to build an array of arrays, and then json_encode the parent array.
$data = array();
$data['fruits'] = array('apple','banana','cherry');
$data['animals'] = array('dog', 'elephant');
$json = json_encode($data);
Following this code, $json will have the following value
{"fruits":["apple","banana","cherry"],"animals":["dog","elephant"]}
It could then be parsed properly by javascript using jQuery.parseJSON()
Just json_encode the entire array.
$ar['key'] = "name";
$json = json_encode($ar);
json_encode returns a string, and json encoding a string will return a string.
Also it's json_encode, not $json_encode
I am trying to get mysql data in to json using php and later access it in url. I am getting data in json but i need in a format. Below is my php code to get json.
header('Content-Type: application/json');
include('dbhconfig.inc.php');
$response = array();
$stmt = $dbh->prepare("SELECT * FROM venderlist");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
{
$response['results'] = $rows;
}
echo json_encode($response);
And my json data showing as bellow
{"results":[{"id":"1","vendname":"Genie Events","address":"15, Lower Ground Floor, Lajpat Nagar, Delhi - 110024, Near National Park ","contact":"(91)-11-33437065","contact_o":"(91)-11-40666522","est":"2010","website":"www.genieevents.com","email":"","zip":"110024","latitude":"1.28525","longitude":"103.775464","latlon":"1.28525,103.775464","type":"organisers"},
First of all its not showing in proper structure. And presently latlon is showing like "latlon":"1.28525,103.775464" but i want result should be "latlon":[1.28525,103.775464]
How to add [] to my json variable name latlon.
If course, you'll need to break down that part of the data first since its a string. You'll need to set them up as an array unit with both float values inside.
After fetching them all, you'll need to make a little bit of operations.
You can use explode on that string first with that ,. So that becomes an array []. But it doesn't end there, the exploded elements are still strings, so you can map out all elements with floatval with the use of arrray_map.
So all in all, it would look just like this:
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as &$r) { // with reference
// explode with comma, map with floatval
$r['latlon'] = array_map('floatval', explode(',', $r['latlon']));
}
echo json_encode(array('results' => $rows)); // json encode
I'm trying to decode the following JSON using php json_decode function.
[{"total_count":17}]
I think the square brackets in output is preventing it. How do I get around that? I can't control the output because it is coming from Facebook FQL query:
https://api.facebook.com/method/fql.query?format=json&query=SELECT%20total_count%20FROM%20link_stat%20WHERE%20url=%22http://www.apple.com%22
PHP's json_decode returns an instance of stdClass by default.
For you, it's probably easier to deal with array. You can force PHP to return arrays, as a second parameter to json_decode:
$var = json_decode('[{"total_count":17}]', true);
After that, you can access the variable as $result[0]['total_count']
See this JS fiddle for an example of how to read it:
http://jsfiddle.net/8V4qP/1
It's basically the same code for PHP, except you need to pass true as your second argument to json_decode to tell php you want to use it as associative arrays instead of actual objects:
<?php
$result = json_decode('[{"total_count":17}]', true);
print $result[0]['total_count'];
?>
if you don't pass true, you would have to access it like this: $result[0]->total_count because it is an array containing an object, not an array containing an array.
$json = "[{\"total_count\":17}]";
$arr = Jason_decode($json);
foreach ($arr as $obj) {
echo $obj->total_count . "<br>";
}
Or use json_decode($json, true) if you want associative arrays instead of objects.
I am new to PHP. I am using json_encode to convert an array into json data, and decode it using json_decode in another file. However, I am getting json error as syntax error.
My code is as follows:
File 1:
$result = get_data_array();
exit(json_encode($result));
File 2:
$result = file_get_contents("http://localhost/file1.php");
$data = json_decode($result,true);
$data->name // name is the array key
However, I am getting an error as:
Trying to get property of non-object.
You passed true to the second parameter of json_decode so it will return an array.
Use this:
$result = file_get_contents("http://localhost/file1.php");
$data = json_decode($result,true);
echo $data['name'];
I have a jQuery post that returns some objects.
So, I have a DB query result that I do json_encode($result) and then I send it as a response in the success function inside the jQuery post.
If I console.log the response I see multiple objects. What I want is to send the response as an array of arrays.
In PHP
json_encode($results)
In javascript:
success: function(json) {
console.log(json);
}
In console log:
[>Object , >Object , >Object]
Any ideas?
Your $results in php is an array of objects or of associative arrays. Make it an array of numerically-indexed arrays before you send with casting:
// ASSUMING each $result object does not have its own nested arrays
foreach ($results as &$result) {
$result = array_values((array) $result);
}
Note you will lose the ability to get items by column name.
But please step back and think about where your $result comes from.
If you are using mysql driver, consider doing this when building your result:
$results = array();
// Note we use MYSQL_NUM option, so $row looks like array('col1value', 'col2value')
while (FALSE !== ($row = mysql_result_array($resource, MYSQL_NUM))) {
$results[] = $row;
}
json_encode($results);
In Javascript with JQuery:
jQuery.makeArray();
http://api.jquery.com/jQuery.makeArray/
In php, casting:
$aArray = (array) $oObject;
json encode will encode a string as a json OBJECT which in javascript is an object. in javascript an array is simply an object with special helper functions. there shouldn't be a need to create an array from the object as you can manipulate an object as easily as you can manipulate an array.