Append data to top of the JSON file using PHP form - php

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;

Related

make json array in json codeigniter

please help, i got stucked on making json using codeigniter.
this is what i want my json look like
{
"pelajar": [
{
"id": "1",
"name": "rumah sakit",
"usia": "45",
"tahun": "2020",
"alamat": "jalan kartini"
},
{
"id": "2",
"name": "rumah sakit umum",
"usia": "28",
"tahun": "2020",
"alamat": "jalan ibu",
"pendidikan": [
{
"id_pelajar": "2",
"sekolah": "SDN Lombok timur"
},
{
"id_pelajar": "2",
"sekolah": "SMPN Lombok timur"
}
]
}
]
}
but, i dont know why my code doesnt work to make like it.
this is how my code output :
{
"pelajar": {
"pelajar": [
{
"id": "1",
"name": "rumah sakit",
"usia": "45",
"tahun": "2020",
"alamat": "jalan kartini"
},
{
"id": "2",
"name": "rumah sakit umum",
"usia": "28",
"tahun": "2020",
"alamat": "jalan ibu"
}
],
"pendidikan": [
{
"id_pelajar": "2",
"sekolah": "SDN Lombok timur"
},
{
"id_pelajar": "2",
"sekolah": "SMPN Lombok timur"
}
]
}
}
this is my code :
$query = $this->db->query("select * from learn") -> result();
$response = array();
$data = array();
$datap = array();
foreach($query as $row){
$data[] = array(
"id"=> $row->id,
"name"=>$row->name,
"usia"=>$row->usia,
"tahun"=>$row->tahun,
"alamat"=>$row->alamat
);
$id = $row->id;
$pendidikanquery = $this->db->query("select * from pendidikan where learn_id='$id'" ) -> result();
foreach($pendidikanquery as $pen){
$datap[] = array(
"id_pelajar"=> $pen->id_pelajar,
"sekolah"=> $pen->sekolah
);
}
}
}
$response['pelajar']['pelajar'] = $data;
$response['pelajar']['pendidikan'] = $datap;
header('Content-Type: application/json');
echo json_encode($response, TRUE);
my problem is to set 'pendidikan' in the pelajar list where id_pelajar from pendidikan is same with id from pelajar table.
Honestly, there is so much to fix, this script should probably be completely rewritten, but I am not prepared to do that from my phone.
I would recommend using Active Record techniques in your model (not your controller).
Cache the subarray data before pushing into the first level. In doing so, you maintain the relationship between the parent id and the subarray data.
To be clear, my snippet will always create a pendidikan subarray -- even if it has no data. If you do not want this behavior, you will need to modify the script to check if the subarray is empty and then conditionally include it into the parent array. If this was my project, I would prefer a consistent data structure so that subsequent process wouldn't need to check again if specific keys exist.
Untested code:
$query = $this->db->query("SELECT * FROM learn")->result();
$data = [];
foreach($query as $row){
$datap = [];
$pendidikanquery = $this->db->query("SELECT * FROM pendidikan WHERE learn_id = {$row->id}")->result();
foreach ($pendidikanquery as $pen) {
$datap[] = [
"id_pelajar" => $pen->id_pelajar,
"sekolah" => $pen->sekolah
];
}
$data[] = [
"id" => $row->id,
"name" => $row->name,
"usia" => $row->usia,
"tahun" => $row->tahun,
"alamat" => $row->alamat,
"pendidikan" => $datap
];
}
header('Content-Type: application/json');
echo json_encode(["pelajar" => $data]);
if you want the output like your first image(the one with a red square)-
$response['pelajar']['pendidikan'] = $datap; // change this one to
// this ↓↓
$response['pelajar']['pelajar']['pendidikan'] = $datap; // change it like this

Append data to top of the JSON file using PHP [duplicate]

This question already exists:
Add new data to top of the JSON file in PHP [duplicate]
Closed 2 years ago.
I am appending data to JSON file using a PHP form, But right now it adds the new data to the bottom in JSON file
I want to add new data to top in JSON file instead of bottom.
Here is My PHP code which i am using to append data to JSON.
<?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;
$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';
}
}
}
?>
Here is the wallpaper.JSON currently it adds data like this -
[
{
"name": "Old Code",
"author": "Old Code",
"category": "Old Code",
"url": "https://wallpaperaccess.com/full/11851.jpg"
},
{
"name": "New Code",
"author": "New Code",
"category": "New Code",
"url": "https://wallpaperaccess.com/full/11851.jpg"
}
]
I want it like this -
[
{
"name": "New Code",
"author": "New Code",
"category": "New Code",
"url": "https://wallpaperaccess.com/full/11851.jpg"
},
{
"name": "Old Code",
"author": "Old Code",
"category": "Old Code",
"url": "https://wallpaperaccess.com/full/11851.jpg"
}
]
Well You can use use array_reverse in your use case but I would do the other approach
$array_data[] = $extra;
$array_data = array_reverse($array_data);
$final_data = json_encode($array_data);
But a better approach would be to use array_unshift
array_unshift($array_data, $extra);
Source: https://www.php.net/manual/en/function.array-unshift.php

how to get this json output into php array

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.

how to update the value of json data label with the new value using php?

I want to update the label value using PHP. Suppose if I enter the same label then it'll match if there exists any same label named, then it'll update the value of that label.
[{
"label": "aa",
"val": "12"
},
{
"label": "new",
"val": "13"
},
{
"label": "yy",
"val": "14"
}]
in that above data.json i want to update the value of label : "yy" to val: "20". For this I'm using this code
$myFile = "data.json";
$arr_data = array(); // create empty array
try
{
//Get form data
$formdata = array(
'label'=> $_POST['label'],
'val' => $_POST['val']
);
//Get data from existing json file
$jsondata = file_get_contents($myFile);
// converts json data into array
$arr_data = json_decode($jsondata, true);
foreach($arr_data as $item){
}
// array_push($arr_data,$formdata);
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
/*this is the matching label code*/
if(in_array($formdata['label'],$item)){
$item['val'] = $formdata['val'];
echo $item['val'];
echo "got it";
}
else echo "not matched";
//write json data into data.json file
if(file_put_contents($myFile, $jsondata)) {
}
else
echo "error";
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Move the code to match label name inside foreach loop so that each label value in json array can be compared. Updated Code:
$myFile = "data.json";
try {
//Get form data
$formdata = array(
'label' => $_POST['label'],
'val' => $_POST['val']
);
//Get data from existing json file
$jsondata = file_get_contents($myFile);
// converts json data into array
$arr_data = json_decode($jsondata, true);
foreach ($arr_data as $key => $item) {
/* this is the matching label code */
if ($formdata['label'] == $item["label"]) {
$arr_data[$key]["val"] = $formdata['val'];
echo $item['val'];
echo "got it";
} else
echo "not matched";
}
//write json data into data.json file
if (!file_put_contents($myFile, json_encode($arr_data, JSON_PRETTY_PRINT))) {
echo "error";
}
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Iterative solution with json_decode() and json_encode()
$jsonData = '[
{
"label": "aa",
"val": "12"
},
{
"label": "new",
"val": "13"
},
{
"label": "yy",
"val": "14"
}
]';
echo '<strong>Before update</strong>';
echo '<pre>';
echo $jsonData;
echo '</pre>';
$jsonArray = json_decode($jsonData, true);
foreach ($jsonArray as $key => $jsonRow) {
if (isset($jsonRow['label']) && $jsonRow['label'] == 'yy') {
$jsonArray[$key]['val'] = 20;
}
}
$jsonData = json_encode($jsonArray, JSON_PRETTY_PRINT);
echo '<strong>After update</strong>';
echo '<pre>';
echo $jsonData;
echo '</pre>';
This code will give output
Before update
[
{
"label": "aa",
"val": "12"
},
{
"label": "new",
"val": "13"
},
{
"label": "yy",
"val": "14"
}
]
After update
[
{
"label": "aa",
"val": "12"
},
{
"label": "new",
"val": "13"
},
{
"label": "yy",
"val": 20
}
]
You can use preg_replace.
The pattern of a Json is very predictable.
Using regex means you don't need to decode and encode or even iterate the array.
$label = "yy";
$val = 20;
echo preg_replace("/label\":\s*\"" . $label . "\",\s*\"val\":\s*\"\d+/",
"label\": \"" . $label . "\", \"val\": \"". $val,
$json);
https://3v4l.org/m4rDa
If you need to know if the label has been updated then you can use this:
$label = "yy";
$val = 20;
$new = Preg_replace("/label\":\s*\"" . $label . "\",\s*\"val\":\s*\"\d+/",
"label\": \"" . $label . "\", \"val\": \"". $val,
$json);
If($json != $new){
Echo "label updated\n";
}else{
Echo "nothing found\n";
}
Echo $new;
It will compare the "old" Json with the new and if they don't match the lable has been updated.

how to create json from associate array

I am new to PHP. So bear with me. I have to fetch songs from db. I don't know how to initialize associate array in a for loop using keyValuePair. and also add status attribute to it.
What i want is
{
"status" : "true" ,// It tells whether day available or not
"data": [
{
"name": "Joe Bloggs",
"id": "203403465"
},
{
"name": "Fred Bloggs",
"id": "254706567"
},
{
"name": "Barny Rubble",
"id": "453363843"
},
{
"name": "Homer Simpson",
"id": "263508546"
}
]
}
My Code
$html = file_get_html('http://1stfold.com/taskbox/Farrukh/Zare/');
$output = array();// how to initialze it in for loop with keyValue pair
// Find all "A" tags and print their HREFs
foreach($html->find('.branded-page-v2-body a') as $e)
{
if (0 === strpos($e->href, '/watch?v'))
{
$output[] = $e->href . '<br>';
echo $e->href . '<br>';
}
}
echo json_encode($output);
Thanks in Advance.
You can add an array to the $output array, by simply changing this :
$output[] = $e->href . '<br>';
To this :
$output['data'][] = array('name' => $name_value, 'id' => $id_value);
This will push arrays to the the $output['data'] array.
You should add the "status" keyValuePair before the loop

Categories