Add data to JSON child array - php

This is my JSON file(database.json):
{
"doctors": [
{
"ID": "ahmadakhavan",
"pass": "1234",
"name": "Ahmad Akhavan",
"profilePic": "address",
},
{
"ID": "akramparand",
"pass": "1234",
"name": "Akram Parand",
"profilePic": "address",
}
],
"games": [
{
"ID": "shuttlefuel_1",
"locked": "0",
"logo": "gameLogo",
},
{
"ID": "birthdaycake",
"locked": "0",
"logo": "gameLogo",
}
],
"users": [
{
"ID": "alirezapir",
"prescribes": [
{
"doctorName": "doctor1",
"done": "yes",
"gameId": "wordschain"
},
{
"doctorName": "doctor2",
"done": "no",
"gameId": "numberlab"
}
],
"profilePic": "address"
},
{
"ID": "amirdibaei",
"pass": "1234",
"profilePic": "address"
}
]
}
I want to add a child under prescribes array for a specific ID.
Below is what I have done in my PHP code to do this:
<?php
$username = $_REQUEST['name'];
$data = $_REQUEST['data'];
//Load the file
$contents = file_get_contents('./database.json');
$arraydata = json_decode($data,true);
//Decode the JSON data into a PHP array.
$contentsDecoded = json_decode($contents, true );
foreach($contentsDecoded['users'] as $item){
if($item['ID'] == $username){
if(!isset($item['prescribes'])){
$item['prescribes'] = Array();
}
array_push($item['prescribes'],$arraydata);
$json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
file_put_contents('./database.json', $json);
exit('1');
exit;
}
}
exit('0');
exit;
?>
If I echo $item['prescribes'] after the line array_push($item['prescribes'],$arraydata); I see data added to it, but the original file (database.json) won't show new added data.
(meaning that this new data is not added to $contentsDecoded)

You have to change foreach() code like below:-
foreach($contentsDecoded['users'] as &$item){ //& used as call by reference
if($item['ID'] == $username){
$item['prescribes'][] = $arraydata; //assign new value directly
$json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
file_put_contents('./database.json', $json);
exit;
}
}

Change your foreach to change the $contentsDecoded array:
foreach($contentsDecoded['users'] as $key => $item){
if($item['ID'] == $username){
if(!isset($item['prescribes'])){
$contentsDecoded['users'][$key]['prescribes'] = Array();
}
array_push($contentsDecoded['users'][$key]['prescribes'],$arraydata);
$json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
file_put_contents('./database.json', $json);
exit('1');
exit;
}
}

Related

nested JSON array to csv in PHP

How can I output this json to csv properly?
My json file pattern is like this:
{
"swimmers": [
{
"Province": "Ontario",
"Exemption": "S9,SB9,SM9",
"Code": "A,3,4",
"Level": "Level 8",
"ClassificationDate": "2020",
"RYEar": "2024",
"Status": "Registered",
"ID": "123456",
"FirstName": "John",
"LastName": "Doe",
"Gender": "M",
"AGE": null,
"DOB": "01/11/2000",
"Clubs": [
{
"Clubname": "Human Fish",
"Code": "ABC",
"Clubid": "300"
}
],
"Email": null,
"Language": "E",
"ChallengeData": null
}
//more entries with same pattern as first
],
"status": "OK",
"application": "SOme App API"
}
I had success to turn it into a csv with the code below but I'm unable to output the clubs field in the csv file, instead of showing the club, it just shows "Array()". I tried to fix that with the commented code but it doesn't solve the problem.
$csvFileName = 'converted.csv';
$json = 'myjson.json';
$data = file_get_contents($json);
$payload= json_decode($data);
$file_pointer = fopen($csvFileName, 'w');
if ($file_pointer){
foreach($payload['swimmers'] as $row) {
// $clubs = $row['Clubs'] ;
// if (is_array($clubs)){
// foreach($clubs as $c){
// fputcsv($file_pointer, $c);
// }
// }else{
fputcsv($file_pointer, $row);
}
}
Append each element of the Clubs field to $row, then remove the Clubs field.
foreach ($payload['swimmers'] as $row) {
foreach ($row['Clubs'] as $club) {
$row = array_merge($row, array_values($club));
}
unset($row['Clubs']);
fputcsv($file_pointer, $row);
}

How to decode this json with foreach

This is the JSON
{
"circuit_list": [
{
"_id": "58c0f378a986f808cdaf94cf",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
},
{
"_id": "58c0f378a986f808cdaf94d0",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
}
}
I already try with this code
$json = json_decode($url, true);
foreach($json as $value)
{
$_id = $value->_id;
}
it didn't work. Please help, I need to get the value to show them on the view. Did I do this wrong? this json is difficult because i didn't understand the structure.
I usually decode json with format
[{"id":"1","name":"faisal"}]
like this and with my foreach it's working.
If the second parameter of json_decode is true, the function will return an array instead of an object. Also, you would need to loop over the circuit_list property of the object.
$json = json_decode($url); // <- remove the parameter
foreach($json->circuit_list as $value) // <- loop over circuit_list
{
$_id = $value->_id;
}
<?php
$json = json_decode($url,true);
foreach($json['circuit_list'] as $value)
{
$id = $value['_id'];
}
?>

Laravel - Format JSON

I have a code that outputs the json result below:
{
"Ghost in the Shell": {
"id": 1203,
"Pipeline": {
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
}
}
Now how can I format it in the my desired json format below:
Note* I have to remove some result.
{
"Ghost in the Shell":
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
Will appreciate if anyone can help me please.
I am not sure what is your purpose , but here is what you need
<?php
$json = '{
"Ghost in the Shell": {
"id": 1203,
"Pipeline": {
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
}
}';
$array = json_decode($json, true);
$newArray = array();
foreach($array as $key=>$value) {
$newArray[$key] = '';
foreach($value as $k=>$v) {
if(is_array($v)) {
$newArray = array_merge($newArray,$v);
}
}
}
$newJson = json_encode($newArray);
echo $newJson;
?>

Illegal string offset. Can't get a child from JSON multi level file

Here's my JSON file:
{
"user": {
"id": "2.8.388387",
"category": "posts",
"json_metadata": {
"tags": [
"new",
],
"image": [
"https://s32.postimg.org/4twcn4yrp/13918652_1345543288792650_1255274463_o.gif"
]
}
}
}
And PHP:
$json = json_decode($content, true);
foreach($json as $i){
$id = $i['id'];
$category = $i['category'];
$image = $i['json_metadata']['image'];
echo $id;
echo $category;
echo $image;
}
Echo $id and $category works just fine. However, $image errors:
Warning: Illegal string offset 'image'
Any ideas what do I miss?
json_metadata is array within loop, so you just need to get data from array as we do in array. it's simple...This will work now foreach loop. you can also print json_metadata array in loop.
$content = '{
"user": {
"id": "example glossary",
"category": "example glossary",
"json_metadata": {
"tags": ["new"],
"image": [
"https://s32.postimg.org/4twcn4yrp/13918652_1345543288792650_1255274463_o.gif"
]
}
}
}';
$json = json_decode($content, true);
foreach ($json as $i) {
$id = $i['id'];
$category = $i['category'];
$image = $i['json_metadata']['image'][0];
echo $id;
echo $category;
echo $image;
}
Try this code
$content = '{
"user": {
"id": "example glossary",
"category": "example glossary",
"json_metadata": {
"tags": ["new"],
"image": [
"https://s32.postimg.org/4twcn4yrp/13918652_1345543288792650_1255274463_o.gif"
]
}
}
}';
$json = json_decode($content, true);
print_r($json['user']['json_metadata']['image'][0]);
You will got:
https://s32.postimg.org/4twcn4yrp/13918652_1345543288792650_1255274463_o.gif

Json php formatted data

I have a json file like this
{
"id": "123456789012345",
"members": {
"data": [
{
"name": "Dylan John",
"administrator": false,
"id": "12341234"
},
{
"name": "Test user",
"administrator": false,
"id": "43214321"
},
{
"name": "Demo user",
"administrator": false,
"id": "55445544"
},
{
"name": "Fake user",
"administrator": false,
"id": "11991199"
}
],
"paging": {
"next": "www.123456demo12345.com"
}
}
}
I need to extract the id of each name.
I just start my php code like that but simply display only the master id:
<?php
$url = "http://www.1234demo1234fake.com/user.json";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
echo $data[id]; //echo master id
echo $data[members][data][id];
?>
You have to iterate over $data['members']['data'] and print $data['members']['data'][$i]['id'].
Your JSON object contains property members again members has property data.
Now data is an array.
Just loop over data, you get array of objects (members), fetch property id from it.
<?php
$abc = json_decode($your_json_sting);
$membersData = $abc->members->data;
$memberIds = array();
foreach ($membersData as $mem) {
$memberIds[] = $mem->id;
}
echo '<pre>';print_r($memberIds);echo '</pre>';
?>

Categories