I'm trying to delete an item from a JSON file using the id of the item.
This is the code I'm using to do so.
if($id){
header('Content-Type: application/json');
$id = $_GET['id'];
$file = file_get_contents("data.json");
$json = json_decode($file);
foreach ($json->items as $item) {
if ($item->id == $id) {
unset($item);
file_put_contents('data.json', json_encode($json));
header('HTTP/1.1 204 No Content');
}
}
}
The RESTclient I'm using gives the 204 but when I look in my JSON file, the item is still there.
Any idea what I'm doing wrong?
EDIT
JSON looks like this
{
"items": [
{
"id": 1,
"title": "title",
"artist": "artist",
"genre": "genre",
"links": [
{
"rel": "self",
"href": "link/webservice/music/1"
},
{
"rel": "collection",
"href": "link/webservice/"
}
]
},
Inside a foreach-loop the copy of the array element you've got does not affect the original array in some ways.
You need to dereference the array item using the original array or pass it to the loop by reference.
The following should work, I guess:
if($id){
header('Content-Type: application/json');
$id = $_GET['id'];
$file = file_get_contents("data.json");
$json = json_decode($file);
foreach ($json->items as $key => $item) {
if ($item->id == $id) {
unset($json->items[$key]);
file_put_contents('data.json', json_encode($json));
header('HTTP/1.1 204 No Content');
}
}
}
Related
I have two JSON files of same format, forexample
1st JSON File
{
"data": {
"business": {
"id": "3NzA0ZDli",
"customers": {
"pageInfo": {
"currentPage": 1,
"totalPages": 695,
"totalCount": 1389
},
"edges": [
{
"node": {
"id": "QnVzaW5lc3M6Z",
"name": "Joe Biden",
"email": "joe#mail.com"
}
},
{
"node": {
"id": "QnVzaW5lc3M6Z",
"name": "MULTIMEDIA PLUMBUM",
"email": "mdi#mail.com"
}
}
]
}
}
}
}
2nd JSON file
{
"data": {
"business": {
"id": "3NzA0ZDli",
"customers": {
"pageInfo": {
"currentPage": 2,
"totalPages": 695,
"totalCount": 1389
},
"edges": [
{
"node": {
"id": "QnVzaW7dQ8N",
"name": "Mark",
"email": "mark#mail.com"
}
},
{
"node": {
"id": "QnVzaW5l5Gy9",
"name": "Trump",
"email": "trump#mail.com"
}
}
]
}
}
}
}
Each user has a unique "id", I want to get their id by searching their name in php, how can I do this
This is my PHP script
$json1 = file_get_contents("1.json");
$json2 = file_get_contents("2.json");
$result1 = json_decode($json1, true);
$result2 = json_decode($json2, true);
foreach ($result2 as $k => $v) {
if ($v['data']['business']['edges']['customers']['node']['name'] == "Trump") break;
}
echo $result[$k]['data']['business']['edges']['customers']['node']['name']; //I want to get id for trump "QnVzaW5l5Gy9"
Each user has a unique "id", I want to get their id by searching their name in php. How can I get id by searching name in both files at a time?
Thanks
Since you are looping through json file it will search inside of "data" so you can't use $v['data']
Also since edges is also array that have same values and you want to search inside of it you must make loop on that also
Here is example
foreach ($result2 as $k => $v) {
foreach ($v['business']['customers']['edges'] as $val) {
if ($val['node']['name'] == 'Trump') {
echo '<pre>';
// and now you can access any of those values, echo $val['node']['id'];
print_r($val['node']);
echo '</pre>';
}
}
}
Output
Array
(
[id] => QnVzaW5l5Gy9
[name] => Trump
[email] => trump#mail.com
)
EDIT
Since you want to search in both files at a same time you can put them into array and then use it like this
$json1 = file_get_contents("1.json");
$json2 = file_get_contents("2.json");
$result1 = json_decode($json1, true);
$result2 = json_decode($json2, true);
$joined_result = array($result1, $result2);
foreach($joined_result as $val) {
// this will take all nodes where you will search
$node = $val['data']['business']['customers']['edges'];
foreach ($node as $value) {
if ($value['node']['name'] == 'Trump') {
echo '<pre>';
print_r($value['node']);
echo '</pre>';
}
}
}
You have two questions there, no?
The first question I get is "How to get the ID for a certain name"
$node = $result2['data']['business']['customers']['edges']['node'];
if ($node['name'] == "Trump") echo $node['id'];
Almost your code, but I echo the ID when the name matches "Trump".
The second question I see is "How do search both json data at once"
$json1 = file_get_contents("1.json");
$json2 = file_get_contents("2.json");
$result1 = json_decode($json1, true);
$result2 = json_decode($json2, true);
$all_data = [$result1, $result2];
foreach($all_data as $data) {
$node = $data['data']['business']['customers']['edges']['node'];
if ($node['name'] == "Trump") echo $node['id'];
}
Transforming both json data to be in an array and then simply looping over the whole array should do the trick.
This question already has answers here:
Get data from JSON file with PHP [duplicate]
(3 answers)
Closed 6 years ago.
I want print specific vars from array inside a document.
JSON structure:
{
"return": {
"string": "2222",
"contacts": [
{
"contact": {
"id": "09890423890"
}
},
{
"contact": {
"id": "2423444"
}
},
{
"contact": {
"id": "24242423"
}
},
etc
]
}
}
I am trying to do this in PHP (and already decoded that json). How can I access and print all ids using foreach or for?
I can not understand how I can manage "return" scope.
You can decode the json contents and use it like an array. This should work:
$json = json_decode($string, true);
$contacts = $json['return']['contacts'];
foreach($contacts as $contact){
echo $contact['contact']['id'];
}
Json decode to array:
$json = json_decode($strjson, true); // decode the JSON into an associative array
and
echo "<pre>";
print_r($json);
And foreach:
foreach ($json as $key => $value) {
echo $key . " ". $value. "<br>";
}
Working example:
$json = '{
"return": {
"string": "2222",
"contacts": [
{
"contact": {
"id": "09890423890"
}
},
{
"contact": {
"id": "2423444"
}
},
{
"contact": {
"id": "24242423"
}
}
]
}
}';
$json = json_decode($json, true);
print_r($json);
foreach ($json['return']['contacts'] as $val) {
echo $val['contact']['id']."<br>";
}
Try this code:
$json ='
{
"return": {
"string": "2222",
"contacts": [
{
"contact": {
"id": "09890423890"
}
},
{
"contact": {
"id": "2423444"
}
},
{
"contact": {
"id": "24242423"
}
},
etc
]
}
}
';
$array = json_decode($json,TRUE);
foreach($array['return']['contacts'] as $value ){
echo $value['id'];
}
Use file_get_contents function if you want to pull data from file.
I have this string -
{
'Carlos':
{
Name: 'Spers',
href: "http://google.com"
},
'Winter':
{
Name: 'Warres',
href: "http://yahoo.com"
},
'Doer':
{
Name: 'Pinto',
href: "http://carpet.com"
}
}
I validated the with JSLinter, it say invalid with multiple errors. And I understand that. The issue is, this is what I get from a third party service. I have to leave with it. Now I'm stuck with it to convert into JSON object to work with it.
When I use json_decode($thisStirng) in PHP, it returns null. $.parseJSON(data) returns me errors too.
I would like to show the data on the webpage with some styling. So at the end, I want json object at the client to work with. So converting data to JSON with PHP or jQuery, anyway would work.
How should I go about it?
Update
I got an associative array with json_decode($thisStirng, true). Now I want echo it as a string so that on browser, I could access it with array indexes.
Thank you all - got it working as below -
$someObject = json_decode($thisStirng,true);
$myarry = array();
foreach ($someObject as $key => $val) {
$temparray = array();
$temparray[]= $key;
$temparray[]= $val;
$myarry[]= $temparray;
}
echo json_encode($myarry);
Now in jQuery I can access, data[index][0] as 'Carlos' and other dynamic keys. data[index][1] is an object with 'Name' and 'href' properies.
You can try this code.
$jsonData='{
"Carlos":
{
"Name": "Spers",
"href": "http://google.com"
},
"Winter":
{
"Name": "Warres",
"href": "http://yahoo.com"
},
"Doer":
{
"Name": "Pinto",
"href": "http://carpet.com"
}
}';
$arr1=array();
$arr2=array();
$arr3=array();
$phpArray = json_decode($jsonData, true);
foreach ($phpArray as $key => $value) {
$arr1=array();
$arr1[]=$key;
foreach ($value as $k => $v) {
$arr2=array();
$arr2[$k]=$v;
$arr3[]=$arr2;
}
}
echo $arr3[0]['Name'];
try using this:
<?php
$jsonData='{
"Carlos":
{
"Name": "Spers",
"href": "http://google.com"
},
"Winter":
{
"Name": "Warres",
"href": "http://yahoo.com"
},
"Doer":
{
"Name": "Pinto",
"href": "http://carpet.com"
}
}';
$phpArray = json_decode($jsonData, true);
foreach ($phpArray as $key => $value) {
echo "Key:".$key. ", Name:". $value['Name'].'<br>';
}
?>
OUTPUT:
Key:Carlos, Name:Spers
Key:Winter, Name:Warres
Key:Doer, Name:Pinto
I'm using PHP and json_decode to use a remote API and I'm having what seems to be a newbie problem for which I didn't even know what to search to find my answer.
So on my script I have a $code = 392 and a json file which simplified version is:
{
"result": {
"items": [
{
"name": "New York",
"code": 7294,
},
{
"name": "Miami",
"code": 392,
},
{
"name": "Los Angeles",
"code": 9182,
}
]
}
}
So, simply put, having the code 392 I want to know which name corresponds to that code. How ?
(The actual json result has thousands of "items", if that makes a difference)
At first you should decode your json data like:
// will decode json data as assoc array
$data = json_decode($json_data, true);
Then, you can get value in this array like:
$item01 = $data['result']['items'][0];
$name = $item01['name']; // New York
$code = $item01['code']; // 7294
Or
// will decode json data as object
$data = json_decode($json_data);
$item01 = $data->result->items[0];
$name = $item01->name; // New York
$code = $item01->code; // 7294
You can iterate through items in result of your JSON object, and check for equality with the desired code, and each item's code. Here's how you would implement it into a function.
function getNameFromCode($json, $code) {
foreach ($json['result']['items'] as $item)
if ($item['code'] == $code)
return $item['name'];
// return false if the code wasn't found.
return false;
}
// assume this is the JSON string of your example.
$json_string = "...";
// pass true as the second argument to get an associative array.
$json = json_decode($json_string, true);
// should return "Los Angeles".
$name = getNameFromCode($json, 9182);
Documenation on foreach().
foreach( json_decode($my_json_string) as $key => $item)
if ( $item['code'] === $code ) { $name = $item[name]; break; }
You can convert JSON to PHP object and loop through the items with foreach loop.
function getNameByCode($phpobj, $code){
if( isset($phpobj->result) ){
if( isset($phpobj->result->items)
&& is_array($phpobj->result->items) ){
foreach($phpobj->result->items as $item){
if( $item->code == $code ){
return $item->name;
}
}
}
}
return false;
}//end function
You can test with this ... NOTE: trailing commas are removed as suggest by rjdown in comment
$json = '{
"result": {
"items": [
{
"name": "New York",
"code": 7294
},
{
"name": "Miami",
"code": 392
},
{
"name": "Los Angeles",
"code": 9182
}
]
}
}';
$phpobj = json_decode($json);
$name = getNameByCode($phpobj, "7294");
echo $name;
I have a jSON file and I want to display its data but it show me result in some strange format i don't know where I'm wrong. Here is my PHP code,
$json = file_get_contents('data.json');
$data = json_decode($json,true);
$users = $data['user'];
foreach($users as $user)
{
echo $user['user'];
}
Data in my jSON file below,
{
"user":
{
"id":"#79F9FFB1EE0CB1CC",
"user":"test#mail.com",
"password":"123456",
"email":"test#mail.com",
"name":"John Doe",
"creationDate":1387111401
},
"status":
{
"version":"0.9.9.1",
"command":"getuser",
"opf":"json",
"error":false,
"code":0
}
}
It's your foreach loop that is wrong.
You only have on user so replace your loop by :
$users = $data['user'];
echo $users['user'];
$json = '{
"user":
{
"id":"#79F9FFB1EE0CB1CC",
"user":"test#mail.com",
"password":"123456",
"email":"test#mail.com",
"name":"John Doe",
"creationDate":1387111401
},
"status":
{
"version":"0.9.9.1",
"command":"getuser",
"opf":"json",
"error":false,
"code":0
}
}';
$data = json_decode($json,true);
$users = $data['user'];
foreach($users as $key=>$user)
{
echo $user.'<br>';
}