i have json file like below:
{
"data": [
{
"id": 8921,
"weather": null,
"status": "TT",
}, {"id": 8922,
"weather": null,
"status": "TF",
},
{
"id": 8923,
"weather": null,
"status": "NT",
}, {"id": 8922,
"weather": null,
"status": "HT",
}
]
}
i read this and show in table
but i want filter that with status and get just status have TF and size depend on.
old code without check status:
$jsonResult = file_get_contents('1.json');
$content_json = json_decode($jsonResult);
$size=sizeof($content_json->data);
the new code (did'nt work true):
$jsonResult = $jsonResult = file_get_contents('1.json');
$content_json = json_decode($jsonResult);
$content_json = array_filter($content_json['data'], function ($data) {
return $data['status'] != 'HT' or $data['status'] != 'NT';
});
You should iterate over the data array to check the status:
$jsonResult = file_get_contents('1.json');
$content_json = json_decode($jsonResult, true);
$data = $content_json['data'];
$filteredData = [];
foreach($data as $entry){
if($entry['status'] == "TF")
$filteredData[] = $entry;
}
$size = sizeof($filteredData);
Also, your JSON file has a syntax error, remove the commas after the status properties like so:
{
"data": [
{
"id": 8921,
"weather": null,
"status": "TT"
}, {"id": 8922,
"weather": null,
"status": "TF"
}
]
}
Using arrays as opposed to objects (pass true as the second parameter to json_decode()), you can use array_filter() to remove any elements your not interested in...
$content_json = json_decode($jsonResult,true);
$content_json = array_filter($content_json['data'], function ($data) {
return $data['status'] == 'TF';
});
echo count($content_json);
Update:
Your code should be...
$content_json = json_decode($jsonResult, true);
$content_json = array_filter($content_json['data'], function ($data) {
return $data['status'] != 'HT' and $data['status'] != 'NT';
});
Note the ,true on the json_decode() and the condition should be and not or.
Related
I use this to retrieve data from url in JSON:
$apiUrl = "https://api.uphold.com/v0/ticker/UPXAU";
$upxau_rates = file_get_contents($apiUrl);
if($upxau_rates !== false){
$upxau_rates_res = json_decode($upxau_rates);
}
foreach($upxau_rates_res as $upxau_rates_item)
{
if($upxau_rates_item->pair == "UPXAU-USD")
{
$usd_rate = $upxau_rates_item->ask;
}
}
JSON from api have this structure:
[{
"ask": "0.27226",
"bid": "0.27226",
"currency": "USD",
"pair": "AEDUSD"
},
{
"ask": "0.02675",
"bid": "0.02675",
"currency": "USD",
"pair": "ARSUSD"
},
{
"ask": "0.72624",
"bid": "0.72624",
"currency": "USD",
"pair": "AUDUSD"
},
...
So, this works fine. But I want to get information about 'ask rate' without 'foreach' and 'if'. For example:
$apiUrl = "https://api.uphold.com/v0/ticker/UPXAU";
$upxau_rates = file_get_contents($apiUrl);
if($upxau_rates !== false){
$upxau_rates_res = json_decode($main_currency);
}
echo $upxau_rates_res['pair']['UPXAU-USD']['ask'];
But this short way not work. How can I get info such short way?
Decode as an array and then index on pair to access it that way. To index all and access ask:
$array = json_decode($json, true);
echo array_column($array, null, 'pair')['AEDUSD']['ask'];
Or to just index the ask on pair:
echo array_column($array, 'ask', 'pair')['AEDUSD'];
To be able to use all of them:
$array = array_column($array, null, 'pair');
echo $array['AEDUSD']['ask'];
This is my JSON file(database.json):
{
"doctors": [
{
"ID": "ahmadakhavan",
"pass": "1234",
"name": "Ahmad Akhavan",
"profilePic": "address",
},
{
"ID": "akramparand",
"pass": "1234",
"name": "Akram Parand",
"profilePic": "address",
}
],
"games": [
{
"ID": "shuttlefuel_1",
"locked": "0",
"logo": "gameLogo",
},
{
"ID": "birthdaycake",
"locked": "0",
"logo": "gameLogo",
}
],
"users": [
{
"ID": "alirezapir",
"prescribes": [
{
"doctorName": "doctor1",
"done": "yes",
"gameId": "wordschain"
},
{
"doctorName": "doctor2",
"done": "no",
"gameId": "numberlab"
}
],
"profilePic": "address"
},
{
"ID": "amirdibaei",
"pass": "1234",
"profilePic": "address"
}
]
}
I want to add a child under prescribes array for a specific ID.
Below is what I have done in my PHP code to do this:
<?php
$username = $_REQUEST['name'];
$data = $_REQUEST['data'];
//Load the file
$contents = file_get_contents('./database.json');
$arraydata = json_decode($data,true);
//Decode the JSON data into a PHP array.
$contentsDecoded = json_decode($contents, true );
foreach($contentsDecoded['users'] as $item){
if($item['ID'] == $username){
if(!isset($item['prescribes'])){
$item['prescribes'] = Array();
}
array_push($item['prescribes'],$arraydata);
$json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
file_put_contents('./database.json', $json);
exit('1');
exit;
}
}
exit('0');
exit;
?>
If I echo $item['prescribes'] after the line array_push($item['prescribes'],$arraydata); I see data added to it, but the original file (database.json) won't show new added data.
(meaning that this new data is not added to $contentsDecoded)
You have to change foreach() code like below:-
foreach($contentsDecoded['users'] as &$item){ //& used as call by reference
if($item['ID'] == $username){
$item['prescribes'][] = $arraydata; //assign new value directly
$json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
file_put_contents('./database.json', $json);
exit;
}
}
Change your foreach to change the $contentsDecoded array:
foreach($contentsDecoded['users'] as $key => $item){
if($item['ID'] == $username){
if(!isset($item['prescribes'])){
$contentsDecoded['users'][$key]['prescribes'] = Array();
}
array_push($contentsDecoded['users'][$key]['prescribes'],$arraydata);
$json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
file_put_contents('./database.json', $json);
exit('1');
exit;
}
}
Hi i am trying to merge output of MySQL result in JSON format but i confused how i can do this so guys i need your helps please tell me how i can do this work thank you.
SQL:
$result = $db->sql_query("SELECT a.*,i.member_id,i.members_seo_name
FROM ".TBL_IPB_USER." i
LEFT JOIN ".TBL_IPB_LA." a
ON a.member_id=i.member_id
WHERE i.".$column." = '".$val."' AND a.game = '".$game."'");
while( $dbarray = $db->sql_fetchrow($result) ){
$arr[] = $dbarray;
}
return ($arr);
The normal result and output with JSON format for my query is:
{
"status": 200,
"result": [
{
"member_id": "1",
"member_name": "maxdom",
"ip_address": "177.68.246.162",
"session_onlineplay": "1",
"sid": "IR63374a32d1424b9288c5f2a5ce161d",
"xuid": "0110000100000001",
"serialnumber": "9923806a06b7f700a6ef607099cb71c6",
"game": "PlusMW3",
"members_seo_name": "maxdom"
},
{
"member_id": "1",
"member_name": "maxdom",
"ip_address": "81.254.186.210",
"session_onlineplay": "1",
"sid": "IR3cd62da2f143e7b5c8f652d32ed314",
"xuid": "0110000100000001",
"serialnumber": "978e2b2668ec26e77c40c760f89c7b31",
"game": "PlusMW3",
"members_seo_name": "maxdom"
}
],
"handle": "checkUSER"
}
But i want to merge output and result like this one:
{
"status": 200,
"result": [
{
"member_id": "1",
"member_name": "maxdom",
"ip_address": [
"177.68.246.162",
"81.254.186.210"
],
"session_onlineplay": "1",
"sid": [
"IR63374a32d1424b9288c5f2a5ce161d",
"IR3cd62da2f143e7b5c8f652d32ed314"
],
"xuid": "0110000100000001",
"serialnumber": [
"9923806a06b7f700a6ef607099cb71c6",
"978e2b2668ec26e77c40c760f89c7b31"
],
"game": "PlusMW3",
"members_seo_name": "maxdom"
}
],
"handle": "checkUSER"
}
you better use php for your parser, prevent high load for database, this is sample code
$result = $db->sql_query("SELECT a.*,i.member_id,i.members_seo_name
FROM ".TBL_IPB_USER." i
LEFT JOIN ".TBL_IPB_LA." a
ON a.member_id=i.member_id
WHERE i.".$column." = '".$val."' AND a.game = '".$game."'");
$arr = array();
while( $dbarray = $db->sql_fetchrow($result) ){
$item = $dbarray;
$item['ip_address'] = array($item['ip_address']);
$item['sid'] = array($item['sid']);
$item['serialnumber'] = array($item['serialnumber']);
$index = $dbarray['member_id'];
if(isset($arr[$index]))
{
$arr[$index]['ip_address'] = array_merge($arr[$index]['ip_address'], $item['ip_address'];
$arr[$index]['sid'] = array_merge($arr[$index]['sid'], $item['sid'];
$arr[$index]['serialnumber'] = array_merge($arr[$index]['serialnumber'], $item['serialnumber']);
} else {
$arr[$index] = $item;
}
}
return array_values($arr);
suppose I have an Array like this :
$myArray =
[
{
"id": 86,
"name": "admin/login"
},
{
"id": 87,
"name": "admin/logout"
},
{
"id": 88,
"name": "admin/desktop"
}
]
Each element of array has json format. and now I want to get name of element that have id of 87 for example.
Firstly How can I found that is there element with this id then get name property of that?
Decode JSON string into array. Then use Laravel's array_first method.
<?php
$myArray = '[{"id": 86,"name": "admin/login"},{"id": 87,"name": "admin/logout"},{"id": 88,"name": "admin/desktop"}]';
// Decode into array
$array = json_decode($myArray, true);
// Find item with correct id
$result = array_first($array, function($key, $value){
return $value['id'] === 87;
}, false);
if ($result) {
echo 'Item found, it\'s name is: '.$result['name'];
}
If you have id you like to find in variable, you have to use use construct.
// ID to search for
$searchID = 87;
// Find item with correct id
$result = array_first($array, function($key, $value) use($searchID){
return $value['id'] === $searchID;
}, false);
Try using this:
$newArray = json_decode($myArray);
and you'll get type of array
[
[
"id"=> 86,
"name"=> "admin/login"
],.....
........
]
Your $myArray is incorrect so, assuming it is a json string you can do this in the following way :
At first json_decode it into an arry.
Loop through the elements to find out you desired value(87).
Keep a flag which will tell if you have actually found any value.
<?php
$myArray =
'[
{
"id": 86,
"name": "admin/login"
},
{
"id": 87,
"name": "admin/logout"
},
{
"id": 88,
"name": "admin/desktop"
}
]';
$myArray = json_decode($myArray , true);
$found = 0;
foreach($myArray as $anArray)
{
if($anArray['id'] == 87)
{
var_dump($anArray['name']);
$found = 1;
}
}
if($found == 1)
{
var_dump("Element found.");
}
else
{
var_dump("Element not found. ");
}
?>
I;m trying to get data from a website using the following code:
<?php
$url = 'http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=4798';
$content = file_get_contents($url);
var_dump($content);
$json = json_decode($content, true);
var_dump($json);
for ($idx = 0; $idx < count($json); $idx++) {
$obj = (Array)$json[$idx];
echo 'result' . $obj["name"];
}
?>
Which is getting me this result:
string(0) "" NULL
<?php
$url = 'http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=4798';
$content = file_get_contents($url);
echo "<pre>";
//print_r($content);
$data = json_decode($content);
print_r($data); //Show the json decoded data comes form $url
##Parse this array {$data} using foreach loop as your use
?>
There are no numeric keys in the json returned from the url you posted in your question. So iterating through the associative array with numeric keys returns nothing.
This is the structure of the json you are working with:
{
"item": {
"icon": "http://services.runescape.com/m=itemdb_oldschool/5122_obj_sprite.gif?id=4798",
"icon_large": "http://services.runescape.com/m=itemdb_oldschool/5122_obj_big.gif?id=4798",
"id": 4798,
"type": "Default",
"typeIcon": "http://www.runescape.com/img/categories/Default",
"name": "Adamant brutal",
"description": "Blunt adamantite arrow... ouch.",
"current": {
"trend": "neutral",
"price": 529
},
"today": {
"trend": "neutral",
"price": 0
},
"members": "true",
"day30": {
"trend": "negative",
"change": "-9.0%"
},
"day90": {
"trend": "negative",
"change": "-20.0%"
},
"day180": {
"trend": "negative",
"change": "-31.0%"
}
}
}
Try accessing $json["item"]. That should give you something more meaningful to work with. If you want to iterate over the key/value pairs in the item, use a foreach loop:
foreach($json["item"] as $key => $value) {
echo $key . ":";
print_r($value);
}