get count of json element(s) in php - php

My json is this :
{
"id1527":{"stats":"true"},
"id6376373":{"stats":"true"},
"id63737":{"stats":"true"}
}
how can get count of all ids(like 'id1527' or 'id6376373'...)

After parsing the JSON, array_filter() to filter this just to the ones with a key that begins with id, and count() to count them:
count(array_filter(json_decode($json, true), function($key) {
return substr($key, 0, 2) == "id";
}, ARRAY_FILTER_USE_KEY));

I hope you mean this.
$str = '{"id1527":{"stats":"true"},"id6376373":{"stats":"true"},"id63737":"stats":"true"},"x444":{"stats":"false"}}';
echo count(preg_grep("/^id(\d)+$/",array_keys(json_decode($str,true))));
This code snippet checks to see whether the top-level key of the JSON array has a preceding text "id" and take only those records into account.

Decode to an array and count the elements.
count(json_decode($json, true));

Related

Get value for JSON key with few dynamic characters

I have a problem statement where I need to find value of a key where I might have to escape few words while searching.
Example :
{"The length is {value} " : "done"}
I should get the output "done" if I search for The length is 10, or The length is 20. I am trying to get this done in php.
First turn your json into an array with json_decode($json, true)
You can create a variable like $key = "The length is" . $number;
And then use key_exist function to check if the $Key exist in your array.
If it exist then you can get the value by key name from your array
decode your json using json_decode() function
get key json array using array_keys() function
get first key pass in json array and get your value
Like this:
$json_array = json_decode($json, true);
$key_array = array_keys($json_array);
echo $json_array[$key_array[0]];

JSON Array Targeting in PHP

I have a JSON i would like to target 'rank' of one of it's object(BTCUSD) in PHP, but the object arrangement is dynamic based on rank.
Below is the JSON output:
{
"tickers":[
{
"pair":"BTCUSD",
"timestamp":153900343434,
"rank":"1",
"bid":"1234.00",
"ask":"1234.00"
},
{
"pair":"BTCGBP",
"timestamp":153900343434,
"rank":"2",
"bid":"54321.00",
"ask":"54321.00"
},
{
"pair":"BTCEUR",
"timestamp":153900343434,
"rank":"3",
"bid":"54321.00",
"ask":"54321.00"
}
]
}
How i am currently getting the result i need:
$arr['RESULT'] = getJson('https://example.com/json')['tickers']['0']['rank'];
echo json_encode($arr)
The above code works, but it's not efficient because when a pair rank changes, it moves up in line and my code will only target the first inline and not BTCUSD pair.
You should search the array then. You could use array_filter.
// Grabbing the json->tickers array
$arr = getJson('https://example.com/json')['tickers'];
// Search the array
$arr = current(array_filter($arr, function($item){
return $item['pair'] == 'BTCUSD';
}));
echo json_encode($arr['rank']);

Finding titles in JSON

I currently have this large JSON file: hastebin
But just want the titles of the posts.
I've tried this...
$json = $page;
$o = json_decode($json, true);
echo($json);
$titles = $o["*"]["*"]["*"]["*"]["title"];
var_dump($titles);
But it isn't working - it's returning NULL! Sometimes it just doesn't return anything.
If anyone is wondering, yes this is from Reddit.
This should do it:
$titles = array_map(function($post) {
return $post['data']['title'];
}, $o['data']['children']);
I'm not sure what you expected using "x" indices, but you should probably read about arrays.
PHP can't use wildcards like * in array keys. Whatever string you use to reference the key, it's going to try to find a key with that exact string. So what you tried can't work because there aren't any * keys.
You can get it by iterating all the levels, or iterating the outer level and referring to the proper nested key. But if you're just looking for all instances of 'title' a recursive method may be an easier way to get them.
array_walk_recursive($o, function($value, $key) use (&$titles) {
if ($key == 'title') $result[] = $value;
});
var_dump($titles);
This will get any value of 'title' regardless of its depth in the array, so if that's not what you want, then you'll need to iterate it and specifically reference the proper ones.
It's very hard to deal directly with such a long JSON document. The returned result from the page is not a valid JSON. It contains some HTML tags, but if you take the posts data and insert it in a file you can do the following according to the structure of your JSON (You can find your JSON in an external link here):
<?php
header("Content-Type:application/json");
$posts=file_get_contents('json.php');
//decode your JSON STRING
$posts=json_decode($posts,true);
//create a title variable to store your titles
$titles=array();
foreach($posts['data']['children'] as $child)
{
array_push($titles,$child['data']['title']);
}
echo json_encode($titles);
?>
You can even use this approach using a URL but ensure that it will return a valid JSON with no html

PHP JSON getting specific value of each key

I have a php code that reads JSON files. Part of the JSON sample below:
"Main": [{
"count": 7,
"coordinates": [89,77],
"description": "Office",
},{
"count": 8,
"coordinates": [123,111],
"description": "Warehouse",
}]
and I am trying to code PHP to only get the info (count, coordinates, description) of those who's description is included in the criteria like Warehouse. PHP Sample below
$validcriteria = array("Warehouse", "Parking_lot");
How do I do an if-statement to check first if "description" is included in the valid criteria. I tried the code below but it doesn't seem to work right.
$JSONFile = json_decode($uploadedJSONFile, false);
foreach ($JSONFile as $key => $value)
{
if (in_array($key['description'] , $validcriteria))
{
#more codes here
}
}
My code in PHP has been working except when I try to add $key['description'] to try and check the description first if it's valid. My code above is reconstructed to remove sensitive information but I hope you got some idea of what I was trying to do.
When attempting to understand the structure of a parsed JSON string, start with a print_r($JSONFile); to examine its contents. In your case, you will find that there is an outer key 'Main' which holds an array of sub-arrays. You will need to iterate over that outer array.
// Set $assoc to TRUE rather than FALSE
// otherwise, you'll get an object back
$JSONFile = json_decode($uploadedJSONFile, TRUE);
foreach ($JSONFile['Main'] as $value)
{
// The sub-array $value is where to look for the 'description' key
if (in_array($value['description'], $validcriteria))
{
// Do what you need to with it...
}
}
Note: if you prefer to continue setting the $assoc parameter to false in json_decode(), examine the structure to understand how the objects lay out, and use the -> operator instead of array keys.
$JSONFile = json_decode($uploadedJSONFile, FALSE);
foreach ($JSONFile->Main as $value)
{
// The sub-array $value is where to look for the 'description' key
if (in_array($value->description, $validcriteria))
{
// Do what you need to with it...
}
}
You might also consider using array_filter() to do the test:
$included_subarrays = array_filter($JSONFile['Main'], function($a) use ($validcriteria) {
return in_array($a['description'], $validcriteria);
});
// $included_subarrays is now an array of only those from the JSON structure
// which were in $validcriteria
Given your JSON structure, you probably want
foreach($decoded_json['Main'] as $sub_array) {
if (in_array($sub_array['description'], $validation)) {
... it's there ...
}
}
Because you set false to second argument of json_decode function, it's returned as an object,
if you change it to TRUE, the code would work.
http://php.net/manual/en/function.json-decode.php
and you have to change key to value;
foreach ($JSONFile->Main as $key => $value)
{
if (in_array($value->description, $validcriteria))
{
#more codes here
}
}
this code assume your json file has one more depth greater than your example. that's why $JSONFile->Main in the foreach loop.
Try to use that :
if ( array_key_exists('description', $key) )

How to get individual fields from JSON in PHP

My JSON looks like this. How do I get a specific field, e.g. "title" or "url"?
{
"status":1,
"list":
{
"204216523":
{"item_id":"204216523",
"title":"title1",
"url":"url1",
},
"203886655":
{"item_id":"203886655",
"title":"titl2",
"url":"url2",
}
},"since":1344188496,
"complete":1
}
I know $result = json_decode($input, true); should be used to get parsable data in $result, but how do I get individual fields out of $result? I need to run through all the members (2 in this case) and get a field out of it.
json_decode() converts JSON data into an associative array. So to get title & url out of your data,
foreach ($result['list'] as $key => $value) {
echo $value['title'].','.$value['url'];
}
echo $result['list']['204216523']['item_id']; // prints 204216523
json_decode() translates your JSON data into an array. Treat it as an associative array because that's what it is.

Categories