I'm using this code $json_output = (json_decode($json, true)); to transform from JSON to an associative array in PHP.
The resulting array looks too compĺex to me, I need to print only some keys and values but they are nested and so far I haven't been able to do it, the examples I had follow for printing are too basic for this.
This is part of my JSON:
{
"project": {
"company": "Company Name SA de CV",
"name": "Project Name",
"files": [
{
"project-id": "666666",
"filenameOnDisk": "HH-ORG-CMD-GUI-File.docx",
"uploaded-date": "2018-01-29T21:20:56Z",
"private": "0",
"version-id": "3939061",
"status": "active",
"tags": [
{
"name": "OPD",
"id": "25047",
"color": "#9e6957"
}
],
"id": "3796128",
"last-changed-on": "2018-01-29T21:21:46Z",
"versions": [],
"uploaded-by-user-first-name": "Someone",
"uploaded-by-user-last-name": "Anything",
"name": "HH-ORG-CMD-GUI-GUIA_RAPIDA_PARA_CREAR_PROCESOS",
"size": "262747",
"category-name": "Instructivos"
},
{
"project-id": "666",
etc...,
},
When parsed looks like
How do I print (lets say) filenameOnDisk and id keys of the Files array.
I don't know how to get to that nested array.
echo $json_output['project']['files'][0]['project-id'];
echo $json_output['project']['files'][0]['filenameOnDisk'];
echo $json_output['project']['files'][0]['version-id'];
Or you could put it in a foreach loop using an array of values you want (as long as they're all in the 'files' array). Eg.
$wantedValues = array("project-id","filenameOnDisk","version-id");
foreach ($wantedValues as $value) {
echo $json_output['project']['files'][0][$value];
}
I Just needed to add a couple of lines at the code provided by #SeeSamRun in order to get the full "Files" array.
$filesArray = $json_output['project']['files'];
$filesSize = count($filesArray);
$wantedValues = array("project-id","filenameOnDisk","version-id");
for ($i=0; $i < $filesSize; $i++) {
foreach ($wantedValues as $value) {
echo $json_output['project']['files'][$i][$value];
}
}
Related
I have multiple JSON files with different structures. What I want to do is to automatically display these JSON outputs with HTML.
Some of my JSON outputs are as follows: (Think of each of these as separate files and need to be processed separately)
{
"parts": [
{
"#attributes": {
"id": "part1"
},
"car": "Peugeot",
"service": 5,
"location": 2996,
"price": "44.95",
"date": "2000-10-01"
},
... other objects
]
}
{
"licenses":[
{
"driver":"John",
"year":26,
"info":null
},
... other objects
]
}
Now, to process these files, I send the page name with GET on PHP and I want the corresponding JSON output to be printed to the screen with HTML as <span>$key</span> -> <span>$value</span>
How can I make this dynamic JSON output read event with PHP? Do I need to create a recursive function?
Because the files have different structures from each other. I hope I was able to explain my problem. Thanks already for yours help.
I suggest the following:
get required JSON file name from GET or POST, for example:
$jsonfilename = $_GET['file'];
The above does not include any security protection! this is a separate topic,
so do some research.
load your json file and parse it:
$json = file_get_contents('/path/'.$jsonfilename);
$data = json_decode($json, true);
read your json data:
foreach ($data as $key=>$value){
echo ''.$key.' -> '.$value.'';
}
A simple example for your PARTS file:
$json = '
{
"parts":
[
{
"#attributes": {
"id": "part1"
},
"car": "Peugeot",
"service": 5,
"location": 2996,
"price": "44.95",
"date": "2000-10-01"
},
{
"#attributes": {
"id": "part2"
},
"car": "Renault",
"service": 8,
"location": 3100,
"price": "99.95",
"date": "2022-03-01"
}
]
}';
$arr = json_decode($json, true);
foreach($arr["parts"] as $part) {
foreach($part as $k => $v){
if($k == "#attributes")
echo "<h1>" . $v["id"] ."</h1>";
else
echo "<span>$k</span> -> <span>$v</span> <br/>";
}
}
This produces:
I'm trying to get JSON by name and save it as a variable with everything related to that nest,
what would the best way to accomplish this?
(in my scenario the names are unique)
[{
"name": "Joe",
"age": "30",
"gender": "male"
},
{
"name": "Logan",
"age": "27",
"gender": "male"
}]
to something like this
{
"Joe": [{
"name": "Joe",
"age": "30",
"gender": "male"
}],
"Logan": [{
"name": "Logan",
"age": "27",
"gender": "male"
}]
}
i need to be able to search on the name to get the correct one, the API switches order so can't get it from just id
Hi This might helps you
$list = '[
{
"name":"Joe",
"age":"30",
"gender":"male"
},
{
"name":"Logan",
"age":"27",
"gender":"male"
}]';
$newjson = json_decode($list, true);
$final = [];
foreach ($newjson as $key => $value) {
$final[$value['name']][]=$value;
}
$finaloutput = json_encode($final, true);
echo "<pre>";
print_r($finaloutput);
echo "</pre>";
exit;
The output is
{"Joe":
[{"name":"Joe","age":"30","gender":"male"}],
"Logan":
[{"name":"Logan","age":"27","gender":"male"}]}
The Laravel Collections Library is a very useful lib to use cases like yours.
For this problem you could use the keyBy method!
$json = '[
{
"name":"Joe",
"age":"30",
"gender":"male"
},
{
"name":"Logan",
"age":"27",
"gender":"male"
}
]';
$array = collect(json_decode($json, true))->keyBy('name')->all();
print_r($array); // will be the array with the keys defined by the name!
See https://laravel.com/docs/5.5/collections#method-keyby
i have an array with a bunch of records like in:
{
"ID": "38424",
"heading": "Nylies soek nuwe hoof",
"typeID": "1",
"datein": "2016-09-26 12:14:16",
"edited_datein": null,
"publishDate": "2016-09-23 00:00:00",
"category": {
"ID": "1",
"heading": "News",
"typeID": "3",
"datein": "2016-09-26 11:50:06",
"edited_datein": null,
"url": "news"
},
"authorID": "592",
"tags": "skool,school,hoof,headmaster,etienne burger"
}
i have another array with "columns" i want the records to be "filtered" by
{
"ID",
"heading",
"datein",
"category|heading",
"category|url"
}
i would like the result to create a multidimensional array based on the column items:
{
"ID": "38424",
"heading": "Nylies soek nuwe hoof",
"datein": "2016-09-26 12:14:16",
"category": {
"heading": "News",
"url": "news"
}
}
how do i achieve this? i'm totally stuck on this now :( busy trying a hack of array_combine now but i dont hold much hope it would work out
so after being stuck on this for many hours.. and posting it here. i found a solution
$new_list = array();
foreach ($n as $record) {
$new_list[] = filter_columns($columns, $record);
}
and the function:
function filter_columns($columns, $record, $pre="") {
$return = array();
foreach ($record as $key => $value) { // loop through the fields in the record
$str = $pre.$key; // create a string of the current key
if (in_array($str,$columns)){
$return[$key] = $value;
}
if (is_array($value)){
$return[$key] = filter_columns($columns, $value,$key."|"); // if the value is an array recall the function but prepend the current key| to the key mask
}
}
return $return;
}
I am trying to decode JSON data to PHP then output it to the site. If I have the following:
{
"name": "josh",
"type": "human"
{
I can do this (within PHP), to display or output my type:
$file = "path";
$json = json_decode($file);
echo $json["type"]; //human
So, if I have the following:
{
"name": "josh",
"type": "human",
"friends": [
{
"name": "ben",
"type": "robot"
},
{
"name": "tom",
"type": "alien"
}
],
"img": "img/path"
}
How can I output what type my friend ben is?
Use a loop like foreach and do something like the following:
//specify the name of the friend like this:
$name = "ben";
$friends = $json["friends"];
//loop through the array of friends;
foreach($friends as $friend) {
if ($friend["name"] == $name) echo $friend["type"];
}
To get the decoded data in array format you would supply true as the second argument to json_decode otherwise it will use the default which is object notation. You could easily create a function to shorten the process when you need to find a specific user
$data='{
"name": "josh",
"type": "human",
"friends": [
{
"name": "ben",
"type": "robot"
},
{
"name": "tom",
"type": "alien"
}
],
"img": "img/path"
}';
$json=json_decode($data);
$friends=$json->friends;
foreach( $friends as $friend ){
if( $friend->name=='ben' )echo $friend->type;
}
function finduser($obj,$name){
foreach( $obj as $friend ){
if( $friend->name==$name )return $friend->type;
}
}
echo 'Tom is a '.finduser($friends,'tom');
try this,
$friend_name = "ben";
$json=json_decode($data);
$friends=$json->friends;
foreach( $friends as $val){
if($friend_name == $val->name)
{
echo "name = ".$val->name;
echo "type = ".$val->type;
}
}
DEMO
Rather new to using json with php, bit of a last resort having searched over the net quite a bit already. I have this example ison file below, which I wish to be able to echo the total number of 'name:' fields within it so eg. 4 in the example below.
Question: How would I go about doing this?
[
{
"age": "22",
"name": "Dave"
},
{
"age": "21",
"name": "Alan"
},
{
"age": "19",
"name": "Luke"
},
{
"age": "30",
"name": "Nina"
}
]
If there will always be a name in each array then just:
echo count(json_decode($json, true));
If name may or not be present in each array then:
PHP >= 5.5.0:
echo count(array_column(json_decode($json, true), 'name'));
PHP < 5.5.0:
$count = 0;
foreach(json_decode($json, true) as $k => $v) {
isset($v['name']) ? $count++ : $count;
}
echo $count;