I am fetching the "form_json" from database which has json saved for all form templates. The code for that is:
<?php
include ('connection.php');
$id = intval($_GET['frmid']);
$results = mysqli_query($conn, "SELECT form_json FROM form WHERE form_id=$id");
while ($row = mysqli_fetch_array($results))
{
$url = $row['form_json'];
echo $url; //Outputs: 2
}
?>
Now, I want to decode all these jsons which are being saved in row form_json. Is there anyway to traverse or something?
$json ='{"value":"Form Title","name":"title"}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
This is how we decode but this is for one string / one form template. I can have many json strings / many form templates saved in database. I should be able to decode all.
The best thing you can do for that is, to store the single json strings into an array. Problem is, that your json strings are encoded, so you need to concat them first if you want all results at once:
$json = array();
$results = mysqli_query($conn, "SELECT form_json FROM form WHERE form_id=$id");
while ($row = mysqli_fetch_array($results)) {
array_push($json, $row['form_json']);
}
$json = implode(",",$json); // concats all json strings with commas
At this point, you have one large string. To make a successful decode, you have to wrap a container around the string to be a valid parse since your values are already json and you need a container for them:
$json = '{"templates": [' . $json . ']}';
Now you have a valid json string that can be decoded, either as array or object. For better understanding a simple working example:
<?php
$json1 = '{"value":"Form Title","name":"title"}';
$json2 = '{"value":"A Message","name":"message"}';
$arr = array($json1, $json2);
$json = implode(",", $arr);
$json = '{"templates": ['.$json.']}';
$json = json_decode($json, true); // true if you want an array, false if you want an object
echo "<pre>";
print_r($json); // returns a multidimensional array of all templates
echo "</pre>";
?>
$json = '{"value":"Form Title","name":"title"}';
$data = json_decode($json);
$value = $data->value; //will output = Form Title
$title = $data->title; //will output = title
i hope this help
Related
I'm working with Laravel 5 right now and I have the following problem. I've got response from DB query:
[{"id":1}]
and I want to take out 1 as int or string. Any ideas?
I've tried to solve this like follows:
$json = (DB query);
$data = json_decode($json);
$final = $data[0]->id;
and response is :
json_decode() expects parameter 1 to be string, array given
This is all you need.
$response = json_decode($response); // Decode the JSON
$string = $response[0]->id; // Save the value of id var
As you say, the string you have is in JSON format, so you need to use json_decode to access it in PHP.
The square brackets refer to an array, and the braces refer to an object within that array, so what you're looking for is the id value of the first element (i.e. element 0) in the array.
<?php
$json = '[{"id":1}]';
$data = json_decode($json);
echo $data[0]->id;
// 1
Try this
$json_array = '[{"id":1}]';
$data = json_decode($json_array);
print_r($data); // To display the result array
You just need to decode it, if I'm not misunderstanding your questions.
$json = '[{"id":1}]';
$decodedObject = json_decode($json);
Then you can loop through the aray and do something with your data:
foreach($decodedObject as $key => $value) {
$id = $value->id;
}
If you're using Laravel, though, why not use Eloquent models?
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 have a table, which I need to echo as json to js. Structure is:
How do I get the data as a json string without extra slashes? I'm not interested in processing params in php or manipulating it in a query, it's used for storage of data (which could vary a lot) and will be used in js side. Using a document based db is not an option at this time.
I have problems with "params", as some extra quotes remain if I try to use stripslashes and invalidates json.
<?php
...
$statement=$pdo->prepare("SELECT params FROM content WHERE id = 19");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
$json = stripslashes($json);
var_dump ($results);
echo "<br/>";
echo $json;
?>
Your fields are already JSON strings. By encoding it, you obtain not valid JSON.
Write in this way:
$data = array();
while( $row = $statement->fetch(PDO::FETCH_ASSOC) )
{
$data[] = ['params'=>json_decode( $row['params'] )];
}
$json = json_encode($data);
echo $json;
This will output a JSON like this:
[
{"params":{"sentence1":"city"}},
(...)
]
If you don't want preserve the “params” key, you can do in this way:
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$data = array_map( 'json_decode', array_column( $results, 'params' ) );
$json = json_encode($data);
echo $json;
This will output a JSON like this:
[
{"sentence1":"city"},
(...)
]
Accepted answer works. Additionally if you want to pass parameter to mapped function in array_map()
Use callback like;
array_map(function ($json) { return json_decode($json, true); }, $res);
i want to know how can i extract a word from a json encoded or decoded.
Example:
From:
{"51973658":{"id":51973658,"name":"Covrigel","profileIconId":748,"summonerLevel":30,"revisionDate":1419865098000}}
I want to see just "Covrigel".
Is that possible?
This is a simple array. You can access that by something like this,
echo $array_name['51973658']['name'];
EDIT after question change:
$json = json_decode($json_array, true);
echo $json['51973658']['name'];
All you have to do is convert it to a PHP array.
$json = '{"51973658":{"id":51973658,"name":"Covrigel","profileIconId":748,"summonerLevel":30,"revisionDate":1419865098000}}';
$json = json_decode($json, $array = true);
echo $json['51973658']['name'];
Decode the JSON as an associative array then echo the value you need.
<?php
$json = '{"51973658":{"id":51973658,"name":"Covrigel","profileIconId":748,"summonerLevel":30,"revisionDate":1419865098000}}';
$data = json_decode($json, true);
echo $data['51973658']['name'];
?>
This is related to Need to display only array value in JSON output asked earlier.
I just want to show only values like
[
"autoComplete",
"ColdFusion",
"jQuery Mobile"
];
Background:
I am using and AJAX call via Jquery mobile to retrieve data from server (language:PHP). I want to use https://github.com/commadelimited/autoComplete.js in my Phonegap Application.
Please advice! I am new to JSON.
when using json_encode, any array that has a zero based numeric index (meaning it is not an associative array and starts with 0 and is not missing any numbers) will be converted to a javascript array instead of a js object literal. You can use array_values in php to get all the values from an array numerically indexed.
<?php
//a generic array
$a = array(
'foo'=>'bar',
'one'=>'two',
'three'=>'four');
//display the array in php
var_dump($a);
echo '<br>';
//json encode it
$json = json_encode($a);
var_dump($json);
echo '<br>';
//json encode just the values
$json = json_encode(array_values($a));
var_dump($json);
http://codepad.viper-7.com/hv06zn
Thanks Jonathan.
However I found the solution as below. I hope that it is useful to someone else too.
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row["title"];
}
mysql_close($con);
echo json_encode($records);