JSON Array Targeting in PHP - 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']);

Related

I have a json file with a list of associative arrays and I need to get it into a php indexed array that I can pull values out of

I cannot figure out how to take a list of associative arrays from a json file and convert it into a php indexed array of associative arrays, and then access the values nested in the associative arrays
Here is the json file
[
{
"homeTeam":"team1",
"homeScore":"00",
"awayTeam":"team2",
"awayScore":"00",
"gameProgression": "Not Started"
},
{
"homeTeam":"team1",
"homeScore":"00",
"awayTeam":"team2",
"awayScore":"00",
"gameProgression": "Not Started"
}
]
And the php code I have been trying to use
$gameFile = file_get_contents("currentGames.json");
$gameFileReady = json_decode($gameFile,true);
$gameArray = array_keys($gameFileReady);
if ($gameArray[0]['gameProgression'] != "Not Started") {
--code--
};
Thanks in advance
array_keys is just going to give you something like Array ( [0] => 0 [1] => 1 ) in this code. So it is unnecessary to achieve what you want.
Simply remove that line and do:
$gameFile = file_get_contents("currentGames.json");
$gameArray = json_decode($gameFile,true);
if (!isset($gameArray[0]['gameProgression'])) {
die('an error occurred');
}
if ($gameArray[0]['gameProgression'] != "Not Started") {
echo 'something';
};
The isset is just for good measure but doesn't change how you access the array item.

get count of json element(s) in 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));

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) )

Convert php multidimensional array to json format to use in Jquery $.post

With fetchAll(PDO::FETCH_ASSOC) get such array
$array =
Array
(
[0] => Array
(
[FinalCurrencyRate] => 0.000062
)
)
Need to json_encode to use in
$.post("__02.php", { 'currency': currency }, function(data, success) {
$('#currency_load').html(data.FinalCurrencyRate);
$('#currency_load0').html(data.FinalCurrencyRate0);
$('#currency_load1').html(data.FinalCurrencyRate1);//and so on
}, "json");
If simply echo json_encode($array); then does not work.
Need to convert to json format array like this:
$arr = array ('FinalCurrencyRate'=>"0.000062");
To convert to json format, wrote such code
$json_array = "{";
$flag_comma = 0;
foreach($array as $i =>$array_modified) {
if ($flag_comma == 0) {
$json_array .="'FinalCurrencyRate". $i."'=>'". $array_modified[FinalCurrencyRate]. "'";
$flag_comma = 1;
}
else {
$json_array .=", 'FinalCurrencyRate". $i."'=>'". $array_modified[FinalCurrencyRate]. "'";
}
}
$json_array .= "}";
Then echo json_encode($json_array);. And only one echo json_encode.
But does not work.
Understand that there are errors in code to convert to json format. What need to correct, please?
If I understand correctly you just want to return the first row form your array, then you just need to do this
echo json_encode($array[0]);
UPDATE
I think I see what you're trying to do now, you're trying to append the index to the FinalCurrencyRate key in each row. No need to do that, what you should do is change your javascript code to look like this:
$('#currency_load0').html(data[0].FinalCurrencyRate);
$('#currency_load1').html(data[1].FinalCurrencyRate);//and so on

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