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;
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 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];
}
}
I have an output from an API, consisting of a list of elements like the following :
{
"data": [
{
"url": "https://parktheater.yesplan.nl/api/event/7036825857-1426512948",
"id": "7036825857-1426512948",
"owner": {
"url": "https://parktheater.yesplan.nl/api/user/365891073-1365159547",
"id": "365891073-1365159547",
"name": "Klaas Seelen"
},
"name": "Ernst, Bobbie en de rest",
"group": {
"url": "https://parktheater.yesplan.nl/api/group/7036832513-1426512948",
"id": "7036832513-1426512948",
"name": "Wij willen water show",
"_type": "group"
},
"starttime": "2016-05-01T16:00:00+02:00",
"endtime": "2016-05-01T18:00:00+02:00",
"locations": [
{
"url": "https://parktheater.yesplan.nl/api/location/383044097-1365160415",
"id": "383044097-1365160415",
"name": "Grote Zaal",
"_type": "location"
}
]
}
This data is provided to me as a string of JSON encoded data, which I stored in a variable $nextevents.
I would like to filter things out, to keep only certain properties of each record :
Name ("ernst, bobbie en de rest")
Group name ("Wij willen water show")
Location type ("Grote zaal")
starttime ("2016-05-01T16:00:00+02:00")
How do I manage that?
Here is how to filter the data :
$json_data = json_decode($nextevents);
$filtered_data = [];
for($i = 0; $i < count($json_data); $i++){
$item = $json_data[$i];
$filtered_data[$i] = array(
"name" => $item["name"],
"group_name" => $item["group"]["name"],
"location_name" => $item["locations"][0]["name"],
"start_time" => $item["starttime"]
);
}
And then you can use it. For example, if you want to output it in a way similar to your example :
for($i = 0; $i < count($filtered_data); $i++){
$item = $filtered_data[$i];
echo "Name : ".$item["name"].", ".
"Group name : ".$item["group_name"].", ".
"Location : ".$item["location_name"].", ".
"Start time : ".$item["start_time"].
"\n");
}
I think the general idea is that to filter the data, the most practical way is to rebuild another object, keeping only what you want.
This is the JSON response that I'm getting from database. I want to print these data. For now, there's only 2 entries in my table. So the length of JSON should be 2. As data increases, count has to get increase. SO for showing output, I use a for loop. And I used count() for limiting the iteration of loop only once through the JSON.
MY JSON:
{
"log": [
{
"action": "qq",
"id": "1",
"Time": "2014-05-19T15:40:06+05:30",
"user": {
"firstName": "dani",
"type": {
"zzs": "1",
"typename": "lolo",
"id": "1",
"zzt": "1",
"zzu": "1",
"zzv": "1",
"zzw": "1",
"zzx": "1"
},
"id": "1",
"lastName": "fed",
"password": "lmfao",
"userName": "fyi"
},
"userIpAddress": "101.15.23.45"
},
{
"action": "vv",
"id": "2",
"Time": "2014-05-20T10:16:33+05:30",
"user": {
"firstName": "dani",
"type": {
"zzs": "1",
"typename": "lolo",
"id": "1",
"zzt": "1",
"zzu": "1",
"zzv": "1",
"zzw": "1",
"zzx": "1"
},
"id": "1",
"lastName": "web",
"password": "rolf",
"userName": "asap"
},
"userIpAddress": "192.168.0.181"
}
]
}
MY PHP
$out = json_decode($json_data, true);
$x= count($out);
echo $x;
The value that I get is 1 instead of 2. And as you can see I have an associative array. I was trying to print those datas.
for($i=0; $i<$x; $i++)
{
echo $out['action'];
echo $out['user'][$i]['firstName'] ;
echo $out['user']['type'][$i]['typename'] ;
}
I don't get output. HELP???
I think it may be counting just the "Log"... technically that response is 2 dimensional:
data[0] = log
data[0][0] = log.firstRecord
data[0][1] = log.secondRecord
Try iterating through the second dimension
you have 2 element inside log key in your array.
try this:
$x= count($out['log']);
this will count 2
demo
for your loop you should try like this:
$out = json_decode($json_data, true);
$x= count($out['log']);
$out = $out['log'];
for($i=0; $i<$x; $i++)
{
echo $out[$i]['action'];
echo $out[$i]['user']['firstName'] ;
echo $out[$i]['user']['type']['typename'] ;
}
complete demo
I am trying to query and parse Yahoo fantasy sports data and show results in a friendly format.
Here is the JSON I get back from Yahoo from a successful request...
{
"fantasy_content": {
"xml:lang": "en-US",
"yahoo:uri": "\/fantasy\/v2\/users;use_login=1\/teams",
"users": {
"0": {
"user": [
{
"guid": "1234567890"
},
{
"teams": {
"0": {
"team": {
"team_key": "268.l.auto.t.209996",
"team_id": "209996",
"name": "Team Test",
"type": "auto"
}
},
"1": {
"team": {
"team_key": "273.l.auto.t.27741",
"team_id": "27741",
"name": "Team API",
"type": "auto"
}
},
"count": 2
}
}
]
},
"count": 1
},
"time": "29.808044433594ms",
"copyright": "Data provided by Yahoo! and STATS, LLC",
"refresh_rate": false
}
}
I am looking to get the team names from the teams array. I have tried using the following PHP code (among countless variations of it) to drill to the node I need but I am not having any luck.
$obj=json_decode($json);
$data = $obj->fantasy_content->users->user->teams->team;
foreach($data as $d){
echo 'name: ' . $d->name ; //prints php
}
I am hoping that someone might be able to provide a working example using the JSON above as I have clearly failed at this. Any help would be greatly appreciated.
Thanks in advance!
Try this
$obj=json_decode($json);
$data = $obj->fantasy_content->users->{'0'}->user[1]->teams;
foreach($data as $d){
echo 'name: ' . $d->team->name ; //prints php
}
EDIT
you can use the cout to loop through the names
$obj=json_decode($json);
$data = $obj->fantasy_content->users->{'0'}->user[1]->teams;
for($i = 0; $i < $data->count; $i++){
echo 'name: ' . $data->{$i}->team->name ; //prints php
}