how to get this json output into php array - php

I want this json output into php array:
{
"data": [
{
"id": "1",
"name": "Roger",
"country": "Switzerland",
"city": "Basel"
},
{
"id": "2",
"name": "Rafael",
"country": "Spain",
"city": "Madrid"
},
]
}
I am trying this:
$arrResult = array();
$arrResult['data'] = array();`
while($row = mysqli_fetch_assoc($result)){`
$id = $row['id'];
$name = $row['name'];
$country = $row['country'];
$arrResult['data'][] = array(
'id'=> $id,
'name'=> $name,
'country'=> $country,
);
}
echo json_encode($arrResult, JSON_FORCE_OBJECT);
I want the same output as given into JSON Format from a php array.

I have found your problem. Remove the comma in the json (explained in the code).
<?php
$json = '{
"data": [
{
"id": "1",
"name": "Roger",
"country": "Switzerland",
"city": "Basel"
},
{
"id": "2",
"name": "Rafael",
"country": "Spain",
"city": "Madrid"
}, <--- THIS IS A PROBLEM
]
}';
/* in order for this function to work you need to delete that comma.
Because there isn't another list in json so comma should not be there */
$arrResult = json_decode($json, true);
print_r($arrResult);

You can use json_decode() if you are using PHP >= 5.2.0
Here is a sample on how to use json_decode()
<?php
// JSON string
$someJSON = '[{"name":"Shriram","gender":"male"},{"name":"Lexa","gender":"female"},{"name":"John Doe","gender":"male"}]';
// Convert JSON string to Array
$someArray = json_decode($someJSON, true);
print_r($someArray); // Dump all data of the Array
echo $someArray[0]["name"]; // Access Array data
// Convert JSON string to Object
$someObject = json_decode($someJSON);
print_r($someObject); // Dump all data of the Object
echo $someObject[0]->name; // Access Object data
?>

you can use the json_decode function.
example;
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
echo $json;
$array = json_decode($json, true);
print_r($array);
?>

What I've understood is that you want to encode your array into the json format shown.
Use json_encode($arrResult) instead of json_encode($arrResult, JSON_FORCE_OBJECT).
JSON_FORCE_OBJECT outputs an object rather than an array.

Related

Append data to top of the JSON file using PHP form

I wanted to append a php from data in JSON file to top.
I used some PHP functions like -
array_unshift($array_data, $extra);
$array_data = array_reverse($array_data);
Example -
<?php
$message = '';
$error = '';
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error = "<label class='text-danger'>Enter Name</label>";
}
else if(empty($_POST["author"]))
{
$error = "<label class='text-danger'>Enter Author</label>";
}
else if(empty($_POST["category"]))
{
$error = "<label class='text-danger'>Enter Thumbnail</label>";
}
else if(empty($_POST["url"]))
{
$error = "<label class='text-danger'>Enter URL</label>";
}
else
{
if(file_exists('wallpaper.json'))
{
$current_data = file_get_contents('wallpaper.json');
$array_data = json_decode($current_data, true);
$extra = array(
'name' => $_POST['name'],
'author' => $_POST["author"],
'category' => $_POST["category"],
'url' => $_POST["url"]
);
$array_data[] = $extra;
//array_unshift($array_data, $extra); // used this as well
$array_data = array_reverse($array_data);
$final_data = json_encode($array_data);
if(file_put_contents('wallpaper.json', $final_data))
{
$message = "<label class='text-success'>File Appended Success fully</p>";
}
}
else
{
$error = 'JSON File not exits';
}
}
}
?>
Both of these PHP functions, they work perfectly until you add data 2 times but once you add 3rd data or more then it looks like this -
[
{
"name": "3",
"author": "3",
"category": "3",
"url": "3"
},
{
"name": "1",
"author": "1",
"category": "1",
"url": "1"
},
{
"name": "2",
"author": "2",
"category": "2",
"url": "2"
}
]
But it should look like this -
[
{
"name": "3",
"author": "3",
"category": "3",
"url": "3"
},
{
"name": "2",
"author": "2",
"category": "2",
"url": "2"
},
{
"name": "1",
"author": "1",
"category": "1",
"url": "1"
}
]
At beggining you have [1] then you insert [2] and after $array_data[] = $extra; goes to [1][2] and the you reverse array [2][1]. At this moment when you insert a new value you have [2][1][3] and the after reversing [3][1][2] the solution would be reversing before insert extra:
test.php:
<?php
if(file_exists('wallpaper.json'))
{
$current_data = file_get_contents('wallpaper.json');
$array_data = json_decode($current_data, true);
$extra = array(
'name' => $_REQUEST['name'],
'author' => $_REQUEST["author"],
'category'=> $_REQUEST["category"],
'url' => $_REQUEST["url"]
);
echo $extra['name'];
$array_data = array_reverse($array_data);
$array_data[] = $extra;
$array_data = array_reverse($array_data);
$final_data = json_encode($array_data);
if(file_put_contents('wallpaper.json', $final_data))
{
$message = "<label class='text-success'>File Appended Success fully</p>";
}
}
?>
to run I used to pass parameters:
http://localhost/test.php?name=4&author=4&category=4&url=4
$posted[] = $_POST;
$current_data = file_get_contents('wallpaper.json');
$decoded = json_decode($current_data,true);
//You merge together posted array values with the current array
//that is in the current file (after decoding the json)
//$posted is first part of the array because you start to merge from that
//array
$new_arr = array_merge($posted, $decoded);
//Encode the new array into JSON and save it
$encoded_json = json_encode($new_arr,);
file_put_contents('wallpaper.json', $encoded_json);
First, don't push the $_POST data into its own subarray. It is already in the correct structure to call array_unshift() directly on it. In other words, you don't need to index it -- unshift will apply the 0 key for you.
Code: (Demo)
$fileContents = '[{"name":"B1","author":"B2","category":"B3","url":"B4"},{"name":"A1","author":"A2","category":"A3","url":"A4"}]';
$array = json_decode($fileContents, true);
$_POST = [
'name' => 'C1',
'author' => 'C2',
'category' => 'C3',
'url' => 'C4',
];
array_unshift($array, $_POST);
echo json_encode($array);
Output:
[{"name":"C1","author":"C2","category":"C3","url":"C4"},{"name":"B1","author":"B2","category":"B3","url":"B4"},{"name":"A1","author":"A2","category":"A3","url":"A4"}]
Secondly, I don't support the notion of building this json file if there is any way that you can avoid it. I mean, as you your file size increases, your server will have to work harder and harder and harder to parse the json, manipulate it, re-encode it every time you want to make a change.
I might recommend that you restructure your file to be a txt file which is a collection of json strings -- all of which are separately written on each line. This way you don't have to unpack and repack your data every time, you just prepend the new json string to the file and walk away. *Caveat, this will fail if the data that you are storing contains newline characters -- I don't know if your project might receive such data.
p.s. If you are not a ultra-purist developer and your incoming data is as tame as it looks from your post, you can hack at the json string and lighten the workload like this:
Code: (Demo)
$newJson = json_encode($_POST);
if ($fileContents) {
$fileContents = substr_replace($fileContents, $newJson . ',', 1, 0);
} else {
$fileContent = '[' . $newJson . ']';
}
echo $fileContents;

Get seperate information about each JSON element

I've JSON as follows:
[
{
"id": "..",
"size": "..",
"task": ".."
},
{
"id": "..",
"size": "..",
"task": "..",
},
...
]
My task is to get plain JSON code for each element (array). So, for every id (seperate element) I would get it's json information (size, task ect...). How can this be done?
Update: Is there any better way than following?
json_decode and then loop over each array (because this would give me decoded version, which I don't want right now, so after this procedure, I'd have to encode result again).
Use json_decode()
<?php
$json = array(array('fname'=> "aman", 'lname' => 'kumar', 'email'=> 'developer.amankr#gmail.com'));
$data = json_encode($json); //[{"fname":"aman","lname":"kumar","email":"developer.amankr#gmail.com"}]
$parse = json_decode($data);
echo $fname = $parse[0]->fname;
echo $lname = $parse[0]->lname;
echo "<br>";
echo $email = $parse[0]->email;
?>

Extract each level data with php

The following is the JSon data.
{
"statusType": "OK",
"entity": [
{
"category": "category1","difficultyLevel": "Easy",
"quizAnswerChoices": [{"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}, {"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}]
}
],
"entityType": "java.util.ArrayList",
"status": 200,
"metadata": {}
}
I need to parse
- entity
- quizAnswerChoices (count the item)
How to retrieve each choiceText etc
Use
$json='{
"statusType": "OK",
"entity": [
{
"category": "category1","difficultyLevel": "Easy",
"quizAnswerChoices": [{"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}, {"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}]
}
],
"entityType": "java.util.ArrayList",
"status": 200,
"metadata": {}
}';
$encodedJson= json_decode($json,true);
$quizAnswerChoices=$encodedJson['entity'][0]['quizAnswerChoices'];
echo 'Count: '.count($quizAnswerChoices);
Use this
$arry = json_decode($json,true);
foreach ($arry['entity'] as $ke => $ve) {
foreach ($ve['quizAnswerChoices'] as $k => $v) {
print_r($v);
}
}
Lets consider you are recieving this json in a variable called "$contents".
All you have to do is decode it:
$decoded = json_decode($contents, true); //True so, the decoded object will be converted into an ssociative array
print_r($decoded);
If you do a json_decode like
$data = json_decode(json_data);
Then $data will be a traversable array
$data['entity']['quizAnswerChoices'] etc
Use json_decode to convert json to array
$dataArray = json_decode($json_string, true)
$dataArray['entity']; // entity
$dataArray['entity']['quizAnswerChoices']; // quizAnswerChoices
$dataArray['entity']['quizAnswerChoices']; // quizAnswerChoices
count($dataArray['entity']['quizAnswerChoices']); // quizAnswerChoices count

How to Parse JSON with PHP?

I can do a var_dump, but when trying to access the values, I am getting errors about the values not being found.
{
"metrics": {
"timers": [
{
"name": "com.android.timer.launchtime",
"startTime": 1232138988989,
"duration_ms": 1900
},
{
"name": "com.android.timer.preroll-load-time",
"startTime": 1232138988989,
"duration_ms": 1000
}
]
}
}
I used the following so far to try and parse it.
$json_file = file_get_contents('test.json');
$json_a = json_decode($json_file,true);
var_dump(json_decode($json_file)); //This works
echo $json_a['name']; //I want to print the name of each (from timers).
Try:
$yourDecodedJSON = json_decode($yourJson)
echo $yourDecodedJSON->metrics->timers[0]->name;
Or you can:
$yourDecodedJSON = json_decode($yourJson, true); // forces array
echo $yourDecodedJSON['metrics']['timers'][0]->name;
In your case, you may want to..
foreach($yourDecodedJSON['metrics']['timers'] as $timer){
echo $timer['name']; echo $timer['duration_ms']; // etc
}
If something fails, use:
echo json_last_error_msg()
To troubleshoot further
You need do it in following manner:-
<?php
$data = '{
"metrics": {
"timers": [
{
"name": "com.android.timer.launchtime",
"startTime": 1232138988989,
"duration_ms": 1900
},
{
"name": "com.android.timer.preroll-load-time",
"startTime": 1232138988989,
"duration_ms": 1000
}
]
}
}';
$new_array = json_decode($data); //convert json data into array
echo "<pre/>";print_r($new_array); //print array
foreach ($new_array->metrics->timers as $new_arr){ // iterate through array
echo $new_arr->name.'<br/>'; // rest you can do also same
}
?>
Output:- https://eval.in/407418

Extracting information from an array in php

Can any one tell me how to extract the 'honda' value out of the array below using php?
{
"version": "1.0",
"encoding": "UTF-8",
"entry": {
"name": "bob",
"car": {
"model": "honda"
}
}
}
This looks like a json encoded object. What you could do is:
$info = json_decode($data, true); //where $data has your stuff from the question
$carModel = $obj['entry']['car']['model'];
If you have all that in a variable called "obj", then
$obj = '{ "version": "1.0", "encoding": "UTF-8", "entry": { "name": "bob", "car": { "model": "honda" } } }';
$arr = json_decode($obj, true);
echo $arr['entry']['car']['model'];
should be 'honda'
EDITED: Per Omar below, you do need the true as the second param in json_decode. He should get selected as the correct answer.
Use json_decode as: http://php.net/manual/fr/function.json-decode.php
<?php
$json = '{"version": "1.0","encoding": "UTF-8","entry": {"name": "bob","car": {"model": "honda"} } }';
$tab = json_decode($json, true);
$honda = $tab['entry']['car']['model'];
var_dump($honda);
// or with object:
$obj = json_decode($json);
$honda = $obj->entry->car->model;
var_dump($honda);

Categories