Get seperate information about each JSON element - php

I've JSON as follows:
[
{
"id": "..",
"size": "..",
"task": ".."
},
{
"id": "..",
"size": "..",
"task": "..",
},
...
]
My task is to get plain JSON code for each element (array). So, for every id (seperate element) I would get it's json information (size, task ect...). How can this be done?
Update: Is there any better way than following?
json_decode and then loop over each array (because this would give me decoded version, which I don't want right now, so after this procedure, I'd have to encode result again).

Use json_decode()
<?php
$json = array(array('fname'=> "aman", 'lname' => 'kumar', 'email'=> 'developer.amankr#gmail.com'));
$data = json_encode($json); //[{"fname":"aman","lname":"kumar","email":"developer.amankr#gmail.com"}]
$parse = json_decode($data);
echo $fname = $parse[0]->fname;
echo $lname = $parse[0]->lname;
echo "<br>";
echo $email = $parse[0]->email;
?>

Related

Append data to top of the JSON file using PHP form

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;

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 can I define an array without a key within another array?

The title sounds a bit confusing, although I'm sure there's a simple solution. I'm using json_encode and am working on a web API. The web API will echo an array that is json_encoded. I want it to look like this:
{
{
"id": "test",
"reason": "test reason"
},
{
{
"id": "test2",
"reason": "test reason2"
}
}
I've tried this:
$array = array();
$array[""] = array();
$array[""]["id"] = "test";
$array[""]["reason"] = "test reason";
$array[""] = array();
$array[""]["id"] = "test";
$array[""]["reason"] = "test reason";
This still has a key though ("") which is annoying. I don't want a key. How can I fix this? Thanks! :)
I think this is more in line with your original code, you nearly had it nailed
<?php
$array = array();
// create 1st detail entry
$arrayDetail = array();
$arrayDetail["id"] = "test";
$arrayDetail["reason"] = "test reason";
$array[] = $arrayDetail; // add detail to array
// create 2nd detail entry
$arrayDetail = array();
$arrayDetail["id"] = "test";
$arrayDetail["reason"] = "test reason";
$array[] = $arrayDetail; // add detail to array
// show the output
var_dump(json_encode($array, JSON_PRETTY_PRINT));
{
{
"id": "test",
"reason": "test reason"
},
{
{
"id": "test2",
"reason": "test reason2"
}
}
This cannot be done for good reason : in javascript, the curly brackets indicate an object. Within an object, each property must have a key. The brackets on the other end indicate a numerically-indexed Array.
The Array type in php may be confusing because it's an all-in-one array, you can mix and match the keys as you see fit.
So this, instead, is valid JSON and might be what you really need (if you don't care about the keys, you'll need to loop over the values):
[
{
"id": "test",
"reason": "test reason"
},
{
{
"id": "test2",
"reason": "test reason2"
}
]
EDIT
You may create such an array in php through json_encode() like this :
$array = [["id"=> "test","reason"=> "test reason"],["id"=> "test","reason"=> "test reason"]];
echo json_encode($array);
You may get such format as below with array_push method,
$array = array();
array_push($array, array('id' => 'test', 'reason' => 'test reason' ) );
echo json_encode($array);
The resut will be a valid json format as
[{"id":"test","reason":"test reason"}]

Cannot retrieve this JSON datas

I tried retrieving the word "John" for example using this way.
Code
$decoded = json_decode('$thejson');
$myvar = $decoded->name;
echo $myvar;
JSON
[
{
"name": "John",
"age": "50",
"Job": "Developer"
}
]
I think the first squarre brackets are the thing blocking me here
Thanks for the help
It should work this way:
$myvar = $decoded[0]->name;
Try this:
$decoded = json_decode($thejson,TRUE);
$myvar = $decoded[0]['name'];

read json like facebook json php

i try to read json by php
{
"data": [
{
"id": "3043252fsdgdf36360354",
"name": "name1",
"access_token": "CAAIf3VEtVSoBAHrVxHL16zt4H5OvwBmdfgs4F3auPE0NZBx5PmIujBAdqw0Cv4bZACXytT1O1y6FHEZA25E1aqQZD"
},
{
"id": "3326848fdgsdfgsdf03424168",
"name": "name2",
"access_token": "CAAIf3VEtVSoBAJinePVdfgsdfgMxuY3zaj9AimaoKx7VIO9jCqZCHC6ZBixL1n6ZC72LTMn0ZB4T8rOHD27WmzbBVgvUwgspeEZD"
}}
i try by this code
$sfgsdfg= $json_a=json_decode($read,true);
echo $json_a['data'][3043252fsdgdf36360354];
echo $json_a['3043252fsdgdf36360354'][access_token];
not working with this php code i need help to read it
i need select access_token by 3043252fsdgdf36360354 as echo $json_a['data'][3043252fsdgdf36360354]['access_token'];
i need only read by id as . mysql command . select access_token where id ='3326848fdgsdfgsdf03424168';
First of all, your JSON is missing a ] character and will cause json_decode to return NULL. You should first correct the JSON string. You can use a online service such as jsonlint.com to validate the JSON. Once you've decoded the JSON string as an associative array, you can just loop through the array and check if it contains the given ID in it. If it does, you can grab the corresponding access token easily.
I've made this into a short little function. You can use that to get the access token by ID:
$jsonArray = json_decode($str, TRUE);
function getAccessTokenFromID($id, $jsonArray) {
foreach ($jsonArray['data'] as $k => $elem) {
if($elem['id'] == $id) {
$access_token = $elem['access_token'];
}
}
return $access_token;
}
Usage:
$myid = '3043252fsdgdf36360354';
$my_accesstoken = getAccessTokenFromID($myid, $jsonArray);
Demo!
Isn't well formed json.
Try with:
{
"data": [
{
"id": "3043252fsdgdf36360354",
"name": "name1",
"access_token": "CAAIf3VEtVSoBAHrVxHL16zt4H5OvwBmdfgs4F3auPE0NZBx5PmIujBAdqw0Cv4bZACXytT1O1y6FHEZA25E1aqQZD"
},
{
"id": "3326848fdgsdfgsdf03424168",
"name": "name2",
"access_token": "CAAIf3VEtVSoBAJinePVdfgsdfgMxuY3zaj9AimaoKx7VIO9jCqZCHC6ZBixL1n6ZC72LTMn0ZB4T8rOHD27WmzbBVgvUwgspeEZD"
}
]
}
And php:
$val = json_decode($read, TRUE);
echo $val['data'][0]['id'];
UPDATED:
function find_by_id($id, $val) {
foreach($val['data'] as $key => $obj) {
if ($obj['id'] === $id)
return $obj['access_token'];
}
}

Categories