Counting results displayed - php

I would like to know how to count how many people follows someone in Instagram and place the number in a var, Instagram gives you this link:
https://api.instagram.com/v1/users/3/followed-by?access_token=xxxxxxxxx.xxxxxxxxxxxxxxxxxxxx
And displays a result like so
{
"data": [{
"username": "meeker",
"first_name": "Tom",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_6623_75sq.jpg",
"id": "6623",
"last_name": "Meeker"
},
{
"username": "Mark",
"first_name": "Mark",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_29648_75sq_1294520029.jpg",
"id": "29648",
"last_name": "Shin"
},
{
"username": "nancy",
"first_name": "Nancy",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_13096_75sq_1286441317.jpg",
"id": "13096",
"last_name": "Smith"
}]
}
How can I count how many are there and place it in a var, lets say:
<? echo "You are been follow by ".$followers." users!"; ?>
To display: You are been follow by 3 users!

You would need to use json_decode to to decode the JSON response, then access the resulting object's data attribute (an array of 'follower' objects), and count that:
$json = '{
"data": [{
"username": "meeker",
"first_name": "Tom",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_6623_75sq.jpg",
"id": "6623",
"last_name": "Meeker"
},
{
"username": "Mark",
"first_name": "Mark",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_29648_75sq_1294520029.jpg",
"id": "29648",
"last_name": "Shin"
},
{
"username": "nancy",
"first_name": "Nancy",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_13096_75sq_1286441317.jpg",
"id": "13096",
"last_name": "Smith"
}]
}';
$json = json_decode($json);
echo "You have " .count($json->data) ." followers"
OR
$json = json_decode($json,true);
echo "You have " .count($json['data']) ." followers"

You are getting as a json string, you need to decode it using json_decode.
$data = json_decode($string,true);
$followers = count($data['data']);
CodePad Demo.

You need to use json_decode() which will return you a PHP array. Then all you need to do is to count() all the values in the array with 'data' key.

You can use json_decode
$array = json_decode($str);
Then give
echo count($array);
It will give total count of users

simple way to count entries returned asJSON
echo count(json_decode($followers);

Use json_decode() to create a PHP array from the JSON. Then you can simply do a count() on that:
$jsonData = json_decode($yourAPIResult);
echo count($jsonData->data);
Be aware, however, that you probably should set up some error handling in case the API did not return a proper JSON string. So something like this might be better:
if (is_null($jsonData) || !property_exists($jsonData, 'data')) {
echo '?';
} else {
echo count($jsonData->data);
}

Related

get array content from json (telegram api) in php

I have this json code
"result": [
{
"update_id": 74783732,
"message": {
"message_id": 852,
"from": {
"id": ---,
"is_bot": false,
"first_name": "---",
"username": "---",
"language_code": "en"
},
"chat": {
"id": ---,
"first_name": "---",
"username": "---",
"type": "private"
},
"date": 1646306224,
"text": "#username",
"entities": [
{
"offset": 0,
"length": 16,
"type": "mention"
}
]
}
}
]
I can get content from update_id , message, first_name etc.
but I want to get "mention" from type how can i do it?
my code is
here i decode json and get arrays from json and put them in variable and use it in my queries but I cant get mention from entities...
$update = file_get_contents("php://input");
$update_array = json_decode($update, true);
if( isset($update_array["message"]) )
{
$text = $update_array["message"]["text"];
$chat_id = $update_array["message"]["chat"]["id"];
}
if(isset($update_array["message"]["entities"]["type"]) and $update_array=="mention")
{
$get_username = $text;
show_users_by_username($get_username);
}
tnx for helping
$update_array will never be equal to "mention" but $update_array["message"]["entities"]["type"] yes.
Change your condition.

PHP convert JSON array to nested

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

Get Json Object from external URL with PHP

I have an URL that returns the JSON object below:
{
"addressList": {
"addresses": [
{
"id": 0000000,
"receiverName": "Name Example",
"country": {
"id": "BRA",
"name": "Brasil"
},
"state": {
"id": "SP"
},
"city": "São Paulo",
"zipcode": "00000000",
"type": "Residential",
"street": "000, St Example",
"number": 00,
"neighborhood": "Example",
"hash": "1bf09357",
"defaultAddress": false,
"notReceiver": false
}
]
}
}
I want to get the state value, how can I retrieve that with PHP?
I tried, something like this, but I couldn't get the state value, that should be SP in this case.
$string = '{ "addressList": { "addresses": [ { "id": xxxxxx, "receiverName": "XXXXX XXXXX", "country": { "id": "BRA", "name": "Brasil" }, "state": { "id": "SP" }, "city": "São Paulo", "zipcode": "03164xxx", "type": "Residential", "street": "Rua xxx", "number": xx, "neighborhood": "xxxxx", "hash": "xxxxx", "defaultAddress": false, "notReceiver": false } ] } }';
$json_o = json_decode($string);
$estado = $json_o->state;
How can I achieve the result I want?
Your JSON is not valid - you can validate it on jsonlint.com (it's invalid due to incorrectly formatted numeric values - "id" : 000000).
From then on, you can decode the value and access your data:
$json_o = json_decode($string);
$estado = $json_o->addressList->addresses[0]->state->id;
If you don't have access to the code that generates the JSON, you can attempt to run a regex to match, replace & wrap the numerical values with ":
$valid_json = preg_replace("/\b(\d+)\b/", '"${1}"', $str);
Note: The above is just an example - you'll have to figure out a case where a numerical value is already wrapped by ".
Your JSON has a couple of syntax errors:
"id": 0000000
"number": 00
JSON doesn't support leading zeros. If precise formatting is important, use strings:
"number": "00"
"id": "0000000"
Alternatively, use well-formed integers in the JSON (saves space) and convert them to formatted strings in PHP.
Once you've fixed your JSON, you can access the state->id value of the first address as I do below. When you decode JSON from an untrusted source, be prepared to do some error handling:
$json_string ="..."; //your source, to be decoded
$json_o= json_decode($json_string);
if(is_null($json_o)): //there was an error decoding
$errno = json_last_error();
$err_msg = json_last_error_msg();
die("Json decode failed: Error #$errno: $err_msg");
endif;
//we get here if json_decode succeeded. To get "SP", do...
$stateID = $json_o->addressList->addresses[0]->state->id;
Try:
$json_o = json_decode($string, true);
$estado = $json_o['addressList']['addresses'][0]['state']['id'];

JSON to HTML table with PHP

How can I display the JSON below in a HTML table with PHP/HTML? I saw some other examples so far but I cant find out how I could use them with my JSON because there is the JSONArray and record section infront of the data.
{"JSONArray":{"record":[{"joined":1396627177212,"name":"kate","rank":"MEMBER","id":"424a0dc79bbb49971a599c80b9d8","dailyCoins-11-9-2015":200},{"joined":1396629936746,"name":"verna","rank":"MEMBER","id":"042896991242f9889d3276f83861","dailyCoins-11-9-2015":590},{"joined":1397048326142,"name":"lucy","rank":"MEMBER","id":"f36ca59409a60a81b110cf6ac714"},{"joined":1411762368798,"name":"christopher","rank":"MEMBER","id":"25108a666d451a923abb19213197","dailyCoins-10-9-2015":880,"dailyCoins-11-9-2015":475},{"id":"b5b733529e4a92ba8f7e2b481290","rank":"MEMBER","joined":1440161306320},{"id":"d2ff8bb9817440aae5c140b81955","rank":"MEMBER","joined":1440611487342},{"id":"e7ede489e4078798fd2c69ee8be6","rank":"MEMBER","joined":1442934056516,"dailyCoins-11-9-2015":460},{"id":"dd9ecd7a5c0f40c265dc6487261c","rank":"MEMBER","joined":1443546076415,"dailyCoins-10-9-2015":520,"dailyCoins-11-9-2015":200},{"id":"aafe27c0544fa394da721aebb220","rank":"MEMBER","joined":1443546124859},{"id":"270bea34095147863c11c7a62ea3","rank":"MEMBER","joined":1443546454759,"dailyCoins-10-9-2015":100},{"id":"a97f1d0ed0a44a928231c6fd9c7c","rank":"MEMBER","joined":1443546461462,"dailyCoins-10-9-2015":400,"dailyCoins-11-9-2015":220},{"id":"4ec268a2d18445a9399a3706b416","rank":"MEMBER","joined":1443546587154,"dailyCoins-11-9-2015":400},{"id":"26114b8edd184483895447d016f5","rank":"MEMBER","joined":1443546851165,"dailyCoins-10-9-2015":50,"dailyCoins-11-9-2015":980},{"id":"cca06c6cfa4cb7b3feb491b2a33c","rank":"MEMBER","joined":1443547050965},{"id":"cba38c69d199448d29bc315f850c","rank":"MEMBER","joined":1443547055696},{"id":"aad9060b693e4dc431687f91f404","rank":"MEMBER","joined":1443547070245,"dailyCoins-10-9-2015":80},{"id":"38876b0a546d44b8bf4f1d224a64","rank":"MEMBER","joined":1443547325591,"dailyCoins-11-9-2015":100},{"id":"6a35e9dfc0e842af93e8200e4d5a","rank":"MEMBER","joined":1443548006094},{"id":"13e287923dcb489c398512066348","rank":"MEMBER","joined":1443548827377},{"id":"a63d75a7db4674h6f2d81efedb1e6","rank":"MEMBER","joined":1443548952273,"dailyCoins-10-9-2015":255},{"id":"1e036c43824736b7a43636652f53","rank":"MEMBER","joined":1443549877348,"dailyCoins-10-9-2015":720,"dailyCoins-11-9-2015":380},{"id":"23a331cfacd844903084c075a04e","rank":"MEMBER","joined":1443549911657,"dailyCoins-10-9-2015":480},{"id":"229638c216a34acd97730b661615","rank":"MEMBER","joined":1443550075437},{"id":"5fa71907e8814cbdcdf730c116b5","rank":"MEMBER","joined":1443550083753,"dailyCoins-10-9-2015":60},{"id":"cbaf32d0c3ab4e9d690655df2ab2","rank":"MEMBER","joined":1443552053749,"dailyCoins-10-9-2015":290},{"id":"684d053c532b4095f100695e86e1","rank":"MEMBER","joined":1443552064766,"dailyCoins-10-9-2015":100,"dailyCoins-11-9-2015":30},{"id":"c9b75606f7e84e91998bc8a905d1","rank":"MEMBER","joined":1443553369085},{"id":"301bfd2965424562d8bc4e633dd3","rank":"MEMBER","joined":1443553480028,"dailyCoins-10-9-2015":130},{"id":"0cf8af3ff14c0984a56fe03562ba","rank":"MEMBER","joined":1443553490690},{"id":"d3e29112b0863cb0c5087d136667","rank":"MEMBER","joined":1443553994063},{"id":"6c1d648ea482429babd18cd151f4","rank":"MEMBER","joined":1443628880615,"dailyCoins-10-9-2015":190,"dailyCoins-11-9-2015":25},{"id":"a5c38d3f77af4678ej40cc069a8ec","rank":"MEMBER","joined":1443811816283,"dailyCoins-10-9-2015":230,"dailyCoins-11-9-2015":25},{"id":"16ab1b04504a33bd504fc72d580c","rank":"MEMBER","joined":1443816233615,"dailyCoins-10-9-2015":125,"dailyCoins-11-9-2015":395},{"id":"1f08be5b8a4ea92d91f24f209ed4","rank":"MEMBER","joined":1444211861989,"dailyCoins-10-9-2015":560,"dailyCoins-11-9-2015":120},{"id":"27adaa178844cbfc02770a443cbf","rank":"MEMBER","joined":1444389831435,"dailyCoins-10-9-2015":200},{"id":"53422792b14b600f46b3a4455930","rank":"MEMBER","joined":1444396739744,"dailyCoins-10-9-2015":670,"dailyCoins-11-9-2015":530},{"id":"3caa1a6c889a4d6e93cba50577a8","rank":"MEMBER","joined":1444397559705,"dailyCoins-10-9-2015":720,"dailyCoins-11-9-2015":820},{"id":"a4de5bb8904b5f474ba64e9760f1","rank":"MEMBER","joined":1444397625609,"dailyCoins-11-9-2015":570},{"id":"be99524ef644ec57d9d46419073f","rank":"MEMBER","joined":1444397712148,"dailyCoins-10-9-2015":780,"dailyCoins-11-9-2015":980},{"id":"9f9a8a5d934024b3e87f7a806bc8","rank":"MEMBER","joined":1444397735181,"dailyCoins-11-9-2015":230},{"id":"86f02fc1ccdee8b8e4e8a960be7d","rank":"MEMBER","joined":1444398374370},{"id":"a738f19606a44a54974b9bbabc4b","rank":"MEMBER","joined":1444398790078,"dailyCoins-10-9-2015":355,"dailyCoins-11-9-2015":160}],"extra":[],"timestamp":1444598000},"api":{}}
Here is the code you want:
$json = '{"users":[{ "user": "Carlos", "age": 30, "country": "Spain" }, { "user": "John", "age": 25, "country": "United States" }, { "user": "Mike", "age": 28, "country": "Canada" }]}';
$arr = json_decode($json, true);
echo "<table><tr><th>user</th><th>age</th><th>country</th></tr>";
foreach($arr['users'] as $item){
echo "<tr><td>".$item['user']."</td><td>".$item['age']."</td><td>".$item['country']."</td></tr>";
}
echo "</table>";
Just convert the json to array and then use a foreach and access each item property.

Error in JSON length returned by PHP count

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

Categories