Retrieve json string stored in mysql field - php

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);

Related

indexing JSON in php after removing item

How can I re-index a JSON after using unset($json -> nodes[$data_deleteNode]) to remove an entry? The common method array_values($json), which usally close the gaps doesn´t work. I understand the error message but do not have an idea to solve it.
array_values() expects parameter 1 to be array, object given
There is a similar thread which refers to the solutions I tried - PHP json_encode as object after PHP array unset() the only difference is the JSON.
If I do not perform any sorting, unset() adds an index which cause my JSON to be not readable for other scripts.
The affected PHP:
<?php
header("Access-Control-Allow-Origin: *");
$data_deleteNode = ($_POST['id']);
$json = file_get_contents("data2.json");
$json = json_decode($json);
//$data_deleteNode = json_decode($data_deleteNode);
//array_splice($json, 3, 1);
printf("%s\n", json_encode($json));
unset($json -> nodes[$data_deleteNode]);
printf("%s\n", json_encode($json));
$json = array_values($json);
$json = json_encode($json);
file_put_contents("data2.json", $json)
?>
UPDATE: modified playground which shows the error https://3v4l.org/XPbuo#v730
$json = file_get_contents("data2.json");
$data = json_decode($json);
unset($data->nodes[$data_deleteNode]);
$data->nodes = array_values($data->nodes);
$json = json_encode($data);
file_put_contents("data2.json", $json)
$data->nodes is the array you're modifying and that you need to reset. You do that with:
$data->nodes = array_values($data->nodes);
Note also that I renamed your variables so $json refers to JSON encoded text, and $data refers to decoded arrays/objects.

How to take out int value from JSON object?

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?

PHP json_Encode an array of json_encode-ed arrays

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

PHP convert json data to php array using json_decode

I insert data using json_decode to MySQL database like this:
["kevin","rode","shure"]
Now I need to convert using json_decode to php array like this:
$selected = array( 'kevin', 'rode', 'shure' );
how do can I convert this?
You can try this
$encoded = '["kevin","rode","shure"]';
$decoded = json_decode($encoded);// or directly pass the value here
print_r($decoded);
And you should get back the encoded array
Convert de data in a string, or get from $_GET or $_POST, it depends of you
$data = '["kevin","rode","shure"]';
$data = json_decode($data);
foreach($data as $name){
echo $name . "<br />";
}
and beware of double quotes
use json_decode with true param to force array output :
$selected = json_decode('["kevin","rode","shure"]', true);
NB : don't forget quotes and see documentation http://php.net/manual/en/function.json-decode.php

Json strings decode mysql

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

Categories