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"
}
}
Related
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);
Below is json code where i have o display its values. How to fetch the output as given below
$jsondata = '{
"flowers": [
{
"id": "1",
"name": "Le Grand Bouquet Blanc",
"price": "65",
"currency": "euro"
},
{
"id": "2",
"name": "Roses",
"price": "33",
"currency": "euro"
},
{
"id": "3",
"name": "Mandarine",
"price": "125",
"currency": "euro"
}
]
}';
Output should come like this
Name : Le Grand Bouquet Blanc, Price : 65
Name : Roses, Price : 33
Name : Mandarine, Price : 125
Total: 223 Euro
Any Help?
JSON decode, loop through the data and output the required text like so:
$data = json_decode($jsondata);
$total = 0;
foreach($data->flowers as &$datum) {
printf('Name : %s, Price: %d'.PHP_EOL, $datum->name, $datum->price);
$total += $datum->price;
}
printf('Total: %d Euro'.PHP_EOL, $total);
Read up on some basic PHP functions/concepts:
http://php.net/manual/en/function.json-decode.php
http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/function.printf.php
http://php.net/manual/en/function.echo.php
http://php.net/manual/en/language.operators.arithmetic.php
Try using json_decode() with true as second attribute to convert JSON it into array first.Then use foreach loop and get desired result.
<?php
$jsondata = '{
"flowers": [
{
"id": "1",
"name": "Le Grand Bouquet Blanc",
"price": "65",
"currency": "euro"
},
{
"id": "2",
"name": "Roses",
"price": "33",
"currency": "euro"
},
{
"id": "3",
"name": "Mandarine",
"price": "125",
"currency": "euro"
}
]
}';
$array = json_decode($jsondata,true);
//print_r($array);
$sum = 0;
foreach($array['flowers'] as $flowers)
{
echo "Name : ".$flowers['name'].",Price : ".$flowers['price'].PHP_EOL;
$sum+=$flowers['price'];
$currency = $flowers['currency'];
}
echo "Total:".$sum." ".$currency;
Try this.
$jsondata = '{
"flowers": [
{
"id": "1",
"name": "Le Grand Bouquet Blanc",
"price": "65",
"currency": "euro"
},
{
"id": "2",
"name": "Roses",
"price": "33",
"currency": "euro"
},
{
"id": "3",
"name": "Mandarine",
"price": "125",
"currency": "euro"
}
]
}';
$data = json_decode($jsondata,true);
echo "Name : " . $data['flowers'][0]['name'] . ' , Price: ' . $data['flowers'][0]['price'] ;
I want to parse an array with PHP's foreach loop to get the object names and values inside the 'ques' array.
[
{
"ques": [
{
"name": "comment",
"value": "comment me for the reason",
"sur_id": "1",
"user_id": "admin#gmail.com",
"pagename": "question_response"
},
{
"name": "check-box[]",
"value": "1"
},
{
"name": "radio",
"value": "radio 2"
},
{
"name": "yes",
"value": "no"
}
]
"ques":[
{
"name": "date",
"value": "2015-10-23"
},
{
"name": "select-deopdown",
"value": ""
},
{
"name": "true",
"value": "false"
},
{
"name": "number",
"value": "55"
}
]
}
]
I want to separate the value from the 'ques' array:
while ($fetch = mysql_fetch_array($query1)) {
$content = $fetch['CONTENT_VALUES'];
// print_r($content);
$content_value= mb_convert_encoding($content ,"UTF-8");
$datas = json_decode($content, true);
foreach($datas->ques as $values)
{
echo $values->value . "\n";
print_r($values);
}
$test[] = array('ques' => $datas ,'answer'=>$values);
}
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"
}
]
}
]
}
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);