Add field to a JSON file - php

I have a very simple JSON file "json.txt" :
{
"status": true,
"data":
{
"clics":
[
{
"id": "1",
"title": "Title 1",
"comment": "Blablabla 1",
"url": "http://photostodisplay/1.jpg"
},
{
"id": "2",
"Title": "Title 2",
"comment": "Blablabla 2",
"url": "http://photostodisplay/2.jpg"
}
]
}
}
and I would like to add data and get the following result :
{
"status": true,
"data":
{
"clics":
[
{
"id": "1",
"title": "Title 1",
"comment": "Blablabla 1",
"url": "http://photostodisplay/1.jpg"
},
{
"id": "2",
"Title": "Title 2",
"comment": "Blablabla 2",
"url": "http://photostodisplay/2.jpg"
},
{
"id": "3",
"Title": "Title 3",
"comment": "Blablabla 3",
"url": "http://photostodisplay/3.jpg"
}
]
}
}
The php code I use return the following error :
Fatal error: Cannot use object of type stdClass as array in /home/XXXX/www/clic/test.php on line 10
Here is the php code
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$file = 'json.txt';
$data = json_decode(file_get_contents($file));
$newdata = array('id'=>'11', 'title' => 'sfdfsdfqf', 'comment' => 'sfdfwwfwdsdfqf', 'url' => 'sdfqwsfsdqqfqqqsfcq');
$data[] = $newdata;
file_put_contents($file, json_encode($data));
echo OK
?>
EDIT - Cezary answer gives almost what I need but is not. Here is what I get :
{
"status": true,
"data": {
"clics": [
{
"id": "1",
"title": "Title 1",
"comment": "Blablabla 1",
"url": "http://photostodisplay/1.jpg"
},
{
"id": "2",
"Title": "Title 2",
"comment": "Blablabla 2",
"url": "http://photostodisplay/2.jpg"
}
]
},
"0": {
"id": "11",
"title": "sfdfsdfqf",
"comment": "sfdfwwfwdsdfqf",
"url": "sdfqwsfsdqqfqqqsfcq"
}
}

The issue lies with this bit of code:
$data = json_decode(file_get_contents($file));
This returns an object, not an associative array. Change that line to this:
$data = json_decode(file_get_contents($file), true);
The second argument in json_decode specifies whether you want an associative array or not, and it defaults to false.
EDIT:
You're currently adding something to the root array. To add to the clics array, you can replace $data[] = $newdata; with:
$data['data']['clics'][] = $newdata;

Shouldn't that be
$data["data"]["clics"][]=$newdata;
or
array_push($data["data"]["clics"],$newdata);

Related

Changing a string in a json object

I'm trying to update a json file and I'm using laravel command to do it. In that file there are specific product codes that need to be changed. The code I'm doing to do this isn't working, it runs but nothing changes.
Here is my code
$old_code = 'P001';
$new_code = 'P011';
$productJson = json_decode(file_get_contents(storage_path('/Product 1/product.json')));
foreach($productJson as $key => $value){
str_replace($old_code, $new_code, $k);
}
file_put_contents(storage_path('/Product 1/product.json), json_encode($productJson, JSON_PRETTY_PRINT));
and this is my json file
{
"P001": {
"name": "Product 1",
"price": "200",
"category": "Shirts"
},
"P002": {
"name": "Product Test",
"price": "100",
"category": "Tops"
},
}
Its probably simpler to read the file and create a new JSON with the new codes like this
$s = '{"P001": {
"name": "Product 1",
"price": "200",
"category": "Shirts"
},
"P002": {
"name": "Product Test",
"price": "100",
"category": "Tops"
},
"P003": {
"name": "Product Test",
"price": "50",
"category": "Bottoms"
}
}';
$old_codes = ['P001', 'P002' ];
$new_codes = ['P011', 'P022' ];
$productJson = json_decode($s);
$new = new stdClass;
foreach($productJson as $key => $json){
$kk = array_search($key, $old_codes);
if ( FALSE !== $kk ) { // found
$new->{$new_codes[$kk]} = $json;
} else {
$new->{$key} = $json;
}
}
echo json_encode($new, JSON_PRETTY_PRINT);
//file_put_contents(storage_path('/Product 1/product.json'), json_encode($new, JSON_PRETTY_PRINT));
RESULT
{
"P011": {
"name": "Product 1",
"price": "200",
"category": "Shirts"
},
"P022": {
"name": "Product Test",
"price": "100",
"category": "Tops"
},
"P003": {
"name": "Product Test",
"price": "50",
"category": "Bottoms"
}
}

How to get json output from php array

This is my PHP code for json output:
$sql="SELECT id,name FROM languages ORDER BY id";
$result=mysqli_query($conn,$sql);
// Fetch all
$result = mysqli_fetch_all($result,MYSQLI_ASSOC);
$out_put = json_encode($result);
echo $out_put;
This is the json output of the above php code:
{
"0": {
"id": "1",
"name": "English"
},
"1": {
"id": "2",
"name": "Kanada"
},
"2": {
"id": "3",
"name": "Hindi"
},
"3": {
"id": "4",
"name": "Telugu"
}
}
But I want output like this:
{
"Responsecode":200,
"Message":"Sucess",
"languagelist": [
{
"id": "1",
"name": "English"
},
{
"id": "2",
"name": "Kannada"
},
{
"id": "3",
"name": "Hindi"
},
{
"id": "4",
"name": "Telugu"
}
]
}
I am trying to create API and I am new in it. Please help. Thank you in advance.
Just write
$out_put = json_encode([
"Responsecode" => 200,
"Message" => "Sucess",
"languagelist" => $result
]);
You can do it by this way:
$output['Responsecode'] = 200;
$output['Message'] = "Sucess";
$output['languagelist'] = $result;
$out_put = json_encode($output);

Filter array elements based on value of a key element for Given IDs

I have a JSON object in PHP Like
$my_json = '[{
"No": "1",
"Id": "10",
"msg": "Value is 10"
},
{
"No": "2",
"Id": "55",
"msg": "value is 55"
}, {
"No": "3",
"Id": "38",
"msg": "value is 38 "
}, {
"No": "4",
"Id": "95",
"msg": "value is 95 "
} ]';
I have converted it to PHP object array using $obj_arr= json_decode($my_json);
Now, based on user selection I want to filter array element
Eg. if the user selects "ID" as 38 and 55 then new array should note have ID 10 and 95 IN it and must contain all other data related to those ID just like an original one
EG
$final_json = '[
{
"No": "2",
"Id": "55",
"msg": "value is 55"
}, {
"No": "3",
"Id": "38",
"msg": "value is 38 "
} ]';
Try this:
<?php
$my_json = '[{
"No": "1",
"Id": "10",
"msg": "Value is 10"
},
{
"No": "2",
"Id": "55",
"msg": "value is 55"
}, {
"No": "3",
"Id": "38",
"msg": "value is 38 "
}, {
"No": "4",
"Id": "95",
"msg": "value is 95 "
} ]';
$selected = [38, 55];
$obj = json_decode($my_json);
$result = array_filter($obj, function($row) use ($selected) {
return in_array($row->Id, $selected);
});
echo json_encode(array_values($result), JSON_PRETTY_PRINT);
Output:
[
{
"No": "2",
"Id": "55",
"msg": "value is 55"
},
{
"No": "3",
"Id": "38",
"msg": "value is 38 "
}
]
If you want to filter out the selected values above instead of keep them, return the negation of in_array.

Simplifying my JSON to build a array.

I am trying to take my JSON input and generate a easy array to search in, but it is as far as I can tell giving me some trouble.
First of, this is my JSON as is, loaded from a file:
{
"teams": [
{
"id": "1",
"boat": "Test",
"name": "Palle Test"
},
{
"id": "2",
"boat": "Test 2",
"name": "Name Test 2"
},
{
"id": "3",
"boat": "Test 3",
"name": "Name Test 3"
},
{
"id": "4",
"boat": "Test 4",
"name": "mller"
}
]
}
Is there a way to simplify this or minimise the number of arrays?
I have been using the following code to preview my array, but I am trying to get it to search for id and then print the values for id, boat and name.
$json_url = "teams.json";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
echo '<pre>';
print_r($data);
echo '</pre>';
This is really quite simple. There is no need to convert a perfectly good object into an array, it only makes life more complex.
The only array you have in your data structure is the teams array and that is easily processed like this
$json = '{
"teams": [
{
"id": "1",
"boat": "Test",
"name": "Palle Test"
},
{
"id": "2",
"boat": "Test 2",
"name": "Name Test 2"
},
{
"id": "3",
"boat": "Test 3",
"name": "Name Test 3"
},
{
"id": "4",
"boat": "Test 4",
"name": "mller"
}
]
}';
$data = json_decode($json);
//print_r($data);
foreach ($data->teams as $object) {
if ( $object->id == 2) {
echo 'boat is ' . $object->boat . ' and name is ' . $object->name . PHP_EOL;
}
}
And the result of the above example would be
boat is Test 2 and name is Name Test 2

remove unnecessary hierarchy from json output

I am building an admin backend for an android app. My code provides a json output which the android developer then uses in his app. The developer asked me if it is possible to reduce the hierarchy level in the json output
as in remove the highlighted []0 and put the contents directly inside the []data instead.
This is my current php code
if($type == 1 ) //Handle item display
{
try
{
$query = "SELECT category FROM category";
$result= $DBH->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
$cat = $row['category'];
$query1 = "SELECT * FROM item WHERE catagory='$cat'";
$value = $DBH->query($query1);
if($row1 = $value->fetchAll(PDO::FETCH_OBJ)){
$main[] = array('data'=>array($row1));
}
else
{
$main[] = array('data'=>array('catagory'=>$row['category']));
}
}
echo json_encode($main);
$result->closeCursor(); //Close database connection free resources
$DBH = null;
}
catch(PDOException $e){
print $e->getMessage ();
die();
}
}
And the json output being generated
[
{
"data": [
[
{
"id": "2",
"name": "rice",
"price": "20",
"description": "Plain Rice",
"image": "4106_rice.jpg",
"time": "12 mins",
"catagory": "Lunch",
"subcat": ""
},
{
"id": "3",
"name": "item 1",
"price": "32",
"description": "item 1 description",
"image": "1370_2Ckjikljklkljh.jpg",
"time": "10",
"catagory": "Lunch",
"subcat": "Chicken Soup"
},
{
"id": "4",
"name": "hello",
"price": "10",
"description": "fgsdjfsfsdj",
"image": "",
"time": "76",
"catagory": "Lunch",
"subcat": ""
}
]
]
},
{
"data": {
"catagory": "Dinner"
}
},
{
"data": {
"catagory": "Soup"
}
},
{
"data": {
"catagory": "Test"
}
}
]
I am not very sure if I can make the changes he asked or if it is possible. Is it doable?
Your json structure is inconsistent and try this approach, will be easier for the developer to parse
{
"response": [
{
"data": [
{
"id": "2",
"name": "rice",
"price": "20",
"description": "Plain Rice",
"image": "4106_rice.jpg",
"time": "12 mins",
"catagory": "Lunch",
"subcat": ""
},
{
"id": "3",
"name": "item 1",
"price": "32",
"description": "item 1 description",
"image": "1370_2Ckjikljklkljh.jpg",
"time": "10",
"catagory": "Lunch",
"subcat": "Chicken Soup"
},
{
"id": "4",
"name": "hello",
"price": "10",
"description": "fgsdjfsfsdj",
"image": "",
"time": "76",
"catagory": "Lunch",
"subcat": ""
}
]
},
{
"data": [
{
"catagory": "Dinner"
}
]
},
{
"data": [
{
"catagory": "Soup"
}
]
},
{
"data": [
{
"catagory": "Test"
}
]
}
]
}

Categories