php update json data based on criteria - php

I have a text file with following json data-
{"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"Sorry, this message is not understandable to me."}}}
{"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"But I will learn this in next few days."}}}
{"sender":"175","time":15,"message":"update next","response":{"recipient":{"id":"17"},"message":{"text":"this will be updated next."}}}
{"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"Anything else you want to ask me?"}}}
I want to update 3rd record based on two criteria:
"id":"17"
"message":"update next"
Output of 3rd record I want -
{"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"Meanwhile, please wait for our representative to get back to you."}}}
please help me to update the record with php.

First of all, you need to make a valid JSON
then you have to convert the JSON to an array
then you have to iterate through the array and find which item matches the criteria
and last you change the values.
JSON file content (filename: items.json):
[
{"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"Sorry, this message is not understandable to me."}}},
{"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"But I will learn this in next few days."}}},
{"sender":"175","time":15,"message":"update next","response":{"recipient":{"id":"17"},"message":{"text":"this will be updated next."}}},
{"sender":"175","time":15,"message":"office app","response":{"recipient":{"id":"17"},"message":{"text":"Anything else you want to ask me?"}}}
]
an example code is provided below:
<?php
$json = file_get_contents('items.json');
$json_as_array = json_decode($json, true);
$found = null;
foreach ($json_as_array as $key => $item)
{
if(strtolower($item['message']) == "update next" && $item['response']['recipient']['id'] == 17)
{
$found = $key;
}
}
$json_as_array[$found] = ["sender" => 175, "time" => 15, "message" => "office app", "response" => [ "recipient" => ["id" => 17], "message" => ["text" => "Meanwhile, please wait for our representative to get back to you."]]];
$json_output = json_encode($json_as_array);
file_put_contents('items.json', $json_output);
echo "Done!";
?>

i will not write all of the code but the proper way of storing the json , the way i do is
file_put_contents('appendData.txt', json_encode($inRadiusPostalCodes) , FILE_APPEND | LOCK_EX);
next when you read the file just read the file with
file_get_contents();
store it in a variable and then json_decode the string and then loop through your array to update record on desired index like
if($index == $someindex){......}

Related

Returning an array from PHP to jQuery from Ajax

I'm trying to get PHP returned array from Ajax.
Here is my Ajax call:
And my PHP code is this:
Query is running perfectly.
I have tried to get values like alert(data[0].program_title) in ajax success. But it also returns Undefined.
How can I fix this issue?
In your PHP code:
//remove
return $data
//change with
echo json_encode($data);
Just before flushing the data back to the stream (returning), convert your data ($data variable in this case) to JSON string using json_encode and add the proper content-type application/json using header function.
However, the best practice is to provide some metadata to your data included in your transfer, like the size of data and count of elements in data and if paginated, which page the data refers to and what the maximum available pages and maximum element size of a page are.
Here's a sample body structure for a more robust data transfer:
$response = [
'page' => 0, // e.g.
'count' => count($data),
'data' => $data,
'max_page' => 3, // e.g.
'item_per_page' => 15, // e.g.
'status_code' => 200, // e.g.
];
header ( "Content-Type: application\/json", true , 200);
return json_encode(
$response
, JSON_INVALID_UTF8_SUBSTITUTE
| JSON_NUMERIC_CHECK
| JSON_PRESERVE_ZERO_FRACTION
| JSON_UNESCAPED_LINE_TERMINATORS
| JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
);
Try this:
$data = [];
if ($numRows>0) {
while($row=$result->fetch_assoc()) {
$data[] = $row;
}
}
Replace return with echo and add json_encode
echo json_encode($data);

order of JSON with multiple arrays in php with varying number of objects

I have never needed json previously, so I have almost zero experience...
I am outputting multiple arrays into a json file using the following code:
$file= 'myfile.json';
$contents = array('name' => $name,'busname' => $busname,'busdesc' => $busdesc, etc, etc);
$newcont=json_encode($contents, JSON_PRETTY_PRINT);
print_r($newcont);
file_put_contents($file, $newcont);
This is working as expected, and the output gives me something similar to this:
"name": [
"joe blogs",
"random name 2",
"random name 3",
etc,
etc
],
"busname": [
"ABC business",
"DEF business",
"HIJ business",
etc,
etc
],
"busdesc": [
"We do stuff",
"We do other stuff",
"We don't do anything",
etc,
etc
],
etc
Is it possible to (with a simple method) have the output to be more like:
"id1": [ "joe blogs", "ABC business", "We do stuff", etc ]
"id2": [ "random name 2", "DEF business", "We do other stuff", etc ]
"id3": [ "random name 3", "HIJ business", "We don't do anything", etc ]
etc
Layout is not particularly important, but getting them grouped together is.
I have had little success with getting relevant results from Google searches.
The reason I ask for a simple method, is that I am sure I can come up with some fancy loop that counts the number of entries first, then loops to keep adding the relevant data - and that may well be the answer, but I just wanted to know.
Many thanks
Edit:
I have undeleted this as my attempt at fixing did not work.
Here is the code:
$results = mysqli_query($con,"SELECT * FROM membersites WHERE id>0 ORDER BY id, busname");
$totalmem = mysqli_num_rows($results);
while($business = mysqli_fetch_array($results))
{
$r1 = $business['id'];
$id[]=$r1;
$r2 = $business['name'];
$name[]=$r2;
$r4 = $business['busname'];
$busname[]=$r4;
$r5 = $business['busdesc'];
$busdesc[]=$r5;
$all[] = "'id:''".$r1."''name:''".$r2."''busname:''".$r4."''busdesc:''".$r5."'";
}
$contents = array('members' => $all);
$newcont=json_encode($contents, JSON_PRETTY_PRINT);
print_r($newcont);
This almost worked as all the data is grouped correctly, however I am only getting one object (members) with all the users inside, not individual objects for each user.
Again, please bare in mind that this is the first project that I have had to output any json files.
Any help will be appreciated :)
Edit 2 (for clarity)
Final output needs to look like this
{
[
{
"id":"1",
"name":"joe blogs",
"busname":"ABC business",
"busdesc":"We do stuff"
},
{
"id":"2",
"name":"joe blogs",
"busname":"random name 2",
"busdesc":"We do other stuff"
},
etc
]
}
This file is going to be read by a mobile app - the app developer has just told me that it need to be in this format.
Apologies for being awkward.
When you loop on your records from DB, build a multi-dimensional array:
while($business = mysqli_fetch_array($results))
{
$all[] = [
'id' => $business['id'],
'name' => $business['name'],
'busname' => $business['busname'],
'busdesc' => $business['busdesc'],
];
// or
$all[] = $business;
// or
$all[ $business['id'] ] = $business;
}
Then you can encode your multidimensional array into JSON like this:
$newcont = json_encode($all, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT);
the addition of JSON_FORCE_OBJECT will preserve numerical keys (i.e. when you add using $all[])
I'd recommend using PDO for database access instead of mysqli, which was originally developed as a stopgap replacement for the old mysql extension. But, using mysqli this should work:
$result = $con->query("SELECT id, name, busname, busdesc FROM membersites WHERE id > 0 ORDER BY id, busname");
$data = $result->fetch_all();
$json = json_encode($data, JSON_PRETTY_PRINT);
file_put_contents($file, $json);
You should avoid using SELECT * when possible. It reduces overhead, and ensures that you know the order of columns you're receiving. The mysqli_result::fetch_all() function pulls all the records at once, so no need for a loop.

Can't display more than one item from amazon product api response

I'm fetching top selling items for a particular browseNodeId. The xml response has 10 items but when I print/display the information it shows only one. Please help.
My request array is:
$params = array(
"Service" => "AWSECommerceService",
"Operation" => "BrowseNodeLookup",
"AWSAccessKeyId" => "",
"AssociateTag" => "",
"BrowseNodeId" => "6386372011",
"ResponseGroup" => "TopSellers"
);
(I removed my ids on purpose)
and this is how I'm parsing xml response:
$response = simplexml_load_file($request_url);
foreach($response->BrowseNodes->BrowseNode as $item)
{
$topItem = $item->TopItemSet->TopItem->Title;
$itemURL = $item->TopItemSet->TopItem->DetailPageURL;
$itemID = $item->TopItemSet->TopItem->ASIN;
$results .= "<tr><td>$topItem</td><td>$itemID</td></tr>";
}
later on I'm simply printing '$results' using echo command. This approach is working with all other requesting/responses i.e. I'm getting & displaying 10 items without any problem. I can't find any error. Please help, I want to display 10 items not just one.
Convert the XML Object into array using this
$response = simplexml_load_file($request_url);
$json_string = json_encode($response);
$result = json_decode($json_string, TRUE);
And then access the elements using array['key'] syntax.

Read and return data from json file in laravel 4

I have a file called data.txt in the public path , it has this
{"data":[{"name": "Jack", "age": 13},{"name": "Mary", "age": 15}]}
and I want to read these data and also return the age for both Jack and Mary,
I know that I can read the file using the decode_json(file_get_contents) but I have no clue how to fetch the data and return specific records from it.
Any help is much appreciated !
You can load the file and decode the content with:
$content = json_decode(file_get_contents($path), true);
This will give you the associative array that contains your JSON content.
You can access data in user objects like that:
$userData = $content['data']; // content of "data" field
$jackData = $userData[0]; // first object in "data" array - Jack
$jackName = $jackData['name']; // Jack's name

Getting values from a PHP Object

I am trying to figure out how to echo the genre value from an object created with this programme wrapper that requests json data from 'The Movie Database'. I'm so stuck and grappling to understand Object-oriented PHP so any help would be great.
I think the fact it is 'nested' (if that's the correct terminology) might be the issue.
<?php
include("tmdb/tmdb-api.php");
$apikey = "myapi_key";
$tmdb = new TMDB($apikey, 'en', true);
$idMovie = 206647;
$movie = $tmdb->getMovie($idMovie);
// returns a Movie Object
echo $movie->getTitle().'<br>';
echo $movie->getVoteAverage().'<br>';
echo '<img src="'. $tmdb->getImageURL('w185') . $movie->getPoster() .'"/></li><br>';
echo $movie->genres->id[28]->name;
?>
All of the other values are echoed just fine but I can't seem to get at genres. The json data looks like this ( some of it).
{
"adult":false,
"backdrop_path":"\/fa9qPNpmLtk7yC5KZj9kIxlDJvG.jpg",
"belongs_to_collection":{
"id":645,
"name":"James Bond Collection",
"poster_path":"\/HORpg5CSkmeQlAolx3bKMrKgfi.jpg",
"backdrop_path":"\/6VcVl48kNKvdXOZfJPdarlUGOsk.jpg" },
"budget": 0,
"genres":[
{ "id": 28, "name": "Action" },
{ "id": 12, "name": "Adventure" },
{ "id": 80, "name": "Crime" }
],
"homepage":"http:\/\/www.sonypictures.com\/movies\/spectre\/",
"id":206647,
"imdb_id":"tt2379713",
"original_language":"en",
"original_title":"SPECTRE",
"overview":"A cryptic message from Bond\u2019s past sends him on a trail to uncover a sinister organization. While M battles political forces to keep the secret service alive, Bond peels back the layers of deceit to reveal the terrible truth behind SPECTRE."
}
$movie->genres->id[28]->name
This assumes that id is an array and you want the item with index number 28 from it. What you want is the item containing an id with the value 28 without knowing its index number.
There's no easy way to get to it. You'd have to loop over the array $movie->genres and output the right one.
Maybe like this:
$n = 28;
// loop over genres-array
foreach($movie->genres as $i=>$g){
// check if id of item has right value and if so print it
if($g->id == $n){
echo $g->name;
// skip rest of loop if you only want one
break;
}
}

Categories