{
"AFL Round 16":{
"4166082":{
"EventID":4166082,
"ParentEventID":3744759,
"MainEvent":"North Melbourne v Hawthorn",
"OutcomeDateTime":"2014-07-06 02:00:00",
"Competitors":{
"Competitors":[
{
"Team":"Hawthorn To Win 40+",
"Win":"3.00"
}
],
"ActiveCompetitors":1,
"TotalCompetitors":1,
"HasWinOdds":true
},
"EventStatus":"Open"
},
"4167064":{
"EventID":4167064,
"ParentEventID":3744759,
"MainEvent":"North Melbourne v Hawthorn",
"OutcomeDateTime":"2014-07-06 02:00:00",
"Competitors":{
"Competitors":[
{
"Team":"Hawthorn (-5.5)",
"Win":"1.86"
},
{
"Team":"North Melbourne (+5.5)",
"Win":"1.86"
}
],
"ActiveCompetitors":2,
"TotalCompetitors":2,
"HasWinOdds":true
},
"EventStatus":"Open"
}
}
}
I am parsing json objects using PHP and here is a sample of my json. Everything is working fine. I just want to check if object property/value exists if yes then throw errors for example i want to check EventID, ParentEventID, OutcomeDateTime, Team (inside Competitors array) are valid property name and they are not null.
This is few lines of my code.
$SortedByDate = array();//Sorted By Date Array i.e key=EventID and value=OutcomeDateTime
//Accessing Root Element0
foreach ($json_a as $root_element => $childnode) {
//Accessing child elements
foreach( $childnode as $cKey => $subChild) {
$OutcomeDateTime_UTC=gmdate('Y-m-d H:i:s', strtotime($subChild['OutcomeDateTime']));
//checking ParentEventID=0 , Competitors array = 2 and OutcomeDateTime is greater than current time + 10 min
if($subChild['ParentEventID']=='0' and is_array($subChild['Competitors']['Competitors']) and count ($subChild['Competitors']['Competitors']) == 2 and $OutcomeDateTime_UTC>=$NewDateTime and !preg_match('/\(Live\)/',$subChild['MainEvent']) ) {
//Inserting values into array
$SortedByDate[$cKey] = $subChild['OutcomeDateTime'];;
}
}
}
I tired to add if(isset($subChild['OutcomeDateTime']) || is_null($subChild['OutcomeDateTime'])) to check if property name is OutcomeDateTime and it is not null and change json proerty's value (OutcomeDateTime) to null but i get an error that "Invalid argument supplied for foreach()"
is there a better way to check property/values before parsing???
Try this and see if it does what you mean. If not, I don't understand. If it does solve your problem I'll explain why...
//Accessing Root Element0
foreach ($json_a as $root_element => &$childnode) {
//Accessing child elements
foreach( $childnode as $cKey => &$subChild) {
$OutcomeDateTime_UTC=gmdate('Y-m-d H:i:s', strtotime($subChild['OutcomeDateTime']));
//checking ParentEventID=0 , Competitors array = 2 and OutcomeDateTime is greater than current time + 10 min
if($subChild['ParentEventID']=='0' && is_array($subChild['Competitors']['Competitors']) && count ($subChild['Competitors']['Competitors']) == 2 && $OutcomeDateTime_UTC>=$NewDateTime && !preg_match('/\(Live\)/',$subChild['MainEvent']) ) {
//Inserting values into array
$SortedByDate[$cKey] = $subChild['OutcomeDateTime'];
}
if(isset($subChild['OutcomeDateTime']) && !is_null($subChild['OutcomeDateTime'])) {
$subChild['OutcomeDateTime'] = null;
}
}
}
I just want to check if object property/value exists if yes then throw errors
Your wording doesn't make sense and little bit odd, maybe you were saying that you want to validate each key (if they exist) and if each value of those keys are not null
for example i want to check EventID, ParentEventID, OutcomeDateTime, Team (inside Competitors array) are valid property name and they are not null.
Here is a fiddle. Try to remove some elements inside the json string to check: Fiddle
$json_a = '{ "AFL Round 16":{ "4166082":{ "EventID":4166082, "ParentEventID":3744759, "MainEvent":"North Melbourne v Hawthorn", "OutcomeDateTime":"2014-07-06 02:00:00", "Competitors":{ "Competitors":[ { "Team":"Hawthorn To Win 40+", "Win":"3.00" } ], "ActiveCompetitors":1, "TotalCompetitors":1, "HasWinOdds":true }, "EventStatus":"Open" }, "4167064":{ "EventID":4167064, "ParentEventID":3744759, "MainEvent":"North Melbourne v Hawthorn", "OutcomeDateTime":"2014-07-06 02:00:00", "Competitors":{ "Competitors":[ { "Team":"Hawthorn (-5.5)", "Win":"1.86" }, { "Team":"North Melbourne (+5.5)", "Win":"1.86" } ], "ActiveCompetitors":2, "TotalCompetitors":2, "HasWinOdds":true }, "EventStatus":"Open" } }}';
$json_a = json_decode($json_a, true);
$json_a = reset($json_a); // ignore these parts since you already know how to get them
$errors = array();
$valid_keys = array('EventID', 'ParentEventID', 'OutcomeDateTime', 'MainEvent', 'Competitors', 'EventStatus');
foreach($json_a as $event_id => $values) {
// check for keys
$keys = array_keys($values);
foreach($valid_keys as $key) {
if(!in_array($key, $keys)) {
// check keys, not valid if it goes here
$errors[] = "<b>$key</b> is missing on your data <br/>";
} else {
// valid keys, check values
if(empty($values[$key])) {
// empty values
$errors[] = "<b>$key</b> has an empty value <br/>";
}
}
}
// next checking, competitors
foreach($values['Competitors']['Competitors'] as $competitors) {
if(empty($competitors)) {
// if competitors is empty
$errors[] = "<b>Competitors</b> has an empty value <br/>";
}
}
}
if(!empty($errors)) {
// not a good error triggering device, just change this to something else
trigger_error('<pre>'.implode($errors).'</pre>', E_USER_ERROR);
}
Related
I have a JSON file which structure looks like this (very simplified):
[
{
"customerId": "M12345",
"houses": [
{
"id": "OBJ12345_1731321200",
"status": {
"id": "4",
"name": "Sold"
}
],
"plots": [
{
"id": "OBJ12345_1771637082",
"status": {
"id": "4",
"name": "Sold"
}
],
"projects": [],
"farms": [],
"commercialPropertys": [],
"condominiums": [],
"foreignProperties": [],
"premises": []
}
]
I have figured out how to count how many "houses" or "plots" there is:
$content = file_get_contents('estateList/estateList.json');
$GetEstateList = json_decode($content);
count($GetEstateList[0]["houses"]);
count($GetEstateList[0]["plots"]);
BUT Trying to figure out using php how to count how many objects which have a condition status(id:4)
I think you will need to use a loop in order to count the objects, i would use a foreach loop, bellow is an example :
$count = 0;
foreach ( $GetEstateList[0] as $key => $value){
if (isset($value['status']) && $value['status']['id'] === "4") {
$count++;
}
}
First, you need to enter the GetEstateList array, then you need to do a cycle for each type (for now types showed are plots and houses), then you need another cycle, because each type is an array of elements and can have more than one estate.
So, try this code:
// Counter variable for condition expressed after (status == 4)
$counter = 0;
// Enter the array and get `customerId`, `houses` and `plots`,
// but we only need the types of estate, so only `houses` and `plots`, in this case
foreach ( $GetEstateList as $estate_array => $array_attr ) {
// We only need `houses` and `plots` (increasing algorithm performance)
if ( $array_attr == "houses" || $array_attr == "plots" ) {
// We're checking all types of estates (all `houses` and all `plots`)
foreach ( $array_attr as $type => $parameter ) {
// So, we can get `status` of every estate
if ( $parameter == "status") {
// And finally we can get `id` for each estate `status`
if ( $parameter["id"] == "4" ) {
$counter++;
}
}
}
}
}
Notice: the code above cannot work if the written JSON structure is too different from the original.
I figured it out myself...
Maybe not the "correct" way but it works! :)
Feel free to comment on any improvement or modifications...
$StatusCount = 0;
foreach ($GetEstateList[0] as $GetEstateType) {
foreach ($GetEstateType as $GetEstate) {
if ($GetEstate["status"]["id"] == "4") {
$StatusCount++;
}
}
}
Heyo newbie to PHP here,
I'm creating a registration form where the user is able to select how many family members are in the family, Depending on the number selected the same number of fields would be created to allow them to enter family members' details.
The form checks if all error messages are empty before starting the database insert.
I've been trying for hours though still not sure what's causing the array to return empty() - False,
Full Code -
GDrive Share Link
Creation of the Arrays
$MemberNameErr = array();
$MemberDOBErr = array();
Giving the Array values based on the number of Family Members
for($Variable_Counter = 0; $Variable_Counter < $Family_Counter;
$Variable_Counter++)
{
$MemberNameErr[$Variable_Counter] = "";
$MemberDOBErr[$Variable_Counter] = "";
}
If function that checks that no errors have been made
if ($FamilyNameErr == "" && $DateErr == "" && $EmailErr == "" && $PhoneErr == "" && $MobileErr == "" && empty($MemberNameErr) && empty($MemberDOBErr))
{
currently using empty() as a way to check if the array is empty
created these just to check if the arrays were Not Empty
if (!empty($MemberNameErr))
{
echo " MEMBER ERROR NOT EMPTY ";
}
if (!empty($MemberDOBErr))
{
echo " DOB ERROR NOT EMPTY ";
}
Thank you for all your input.
In your loop
for($Variable_Counter = 0; $Variable_Counter < $Family_Counter; $Variable_Counter++)
{
$MemberNameErr[$Variable_Counter] = "";
$MemberDOBErr[$Variable_Counter] = "";
}
You're assigning empty string to indexes of the array. This means the array isn't empty anymore.
In example :
$tab = array("", "", "");
if (empty($tab))
{
echo "Empty";
}
else
{
echo "Not empty";
}
Output :
Not empty
A workaround could be to iterate through this array and check if there's at least 1 non empty string.
In example
function CheckNonEmptyValue($arr)
{
foreach ($arr as $value)
{
if (!empty($value))
{
return (true);
}
}
return (false);
}
if (CheckNonEmptyValue($MemberNameErr))
{
echo " MEMBER ERROR NOT EMPTY ";
}
if (CheckNonEmptyValue($MemberDOBErr))
{
echo " DOB ERROR NOT EMPTY ";
}
I have a JSON array that I am pulling values from per $vars. Within the JSON data are going to be some key words that I am looking for. I have a single if else that looks like:
(demonstration purposes)
if( $FullName == $Data[$c]['manager'] $FullName == $Data[$c]['leader'] || $FullName == $Data[$c]['helper']) {
$cheapLabor = 'NO';
} else {
$cheapLabor = 'YES';
}
That works great however, now I want to define more specifically some if else points on status points which would represent their employement status. Each Emp Status is based on a group.
I would need it to check from the top of the food chain, then go downward to check if status = x. If it does then $cheapLabor = 'y'; else $cheapLabor = 'z';
I tried doing it, but I can't seem to get it to work. Here is what I am working with:
$repData = json_decode($json, TRUE);
$c = 0;
$var = $repData[$c]['column'];
if($FullName == $repData[$c]['ceo']) {
$groups = '[13]';
} else {
$groups = '[5]';
}
if($FullName == $repData[$c]['director']) {
$groups = '[10]';
} else {
$groups = '[5]';
}
if($FullName == $repData[$c]['regional']) {
$groups = '[9]';
} else {
$groups = '[5]';
}
if($FullName == $repData[$c]['project_manager']) {
$groups = '[8]';
} else {
$groups = '[]';
}
if($FullName == $repData[$c]['team_leader']) {
$groups = '[6]';
} else {
$groups = '[5]';
}
if($FullName == $repData[$c]['rae']) {
$groups = '[5]';
} else {
$staus = '[5]';
}
Shomz Answer partial working...
$groups = '[4]'; // new hire group default, to be overwritten if a user has the correct title within Table.
$roleGroups = array(
'regional' => '[7]',
'team_leader' => '[6]',
'RAE' => '[5]'
);
foreach ($roleGroups as $role => $groups) { // go through all the Position Titles
if ($FullName == $repData[$c][$role]) { // see if there's a match
$repGroup = $groups; // if so, assign the group
}
}
It sets team_leader and regional correctly but anything else just sets it as regional group.
Just realized that its actually rewriting the value.
Your code is overwriting $groups in every if-statement. You probably want to rewrite that in a switch/case statement with a default value being [5].
Let's say the first if is true, so $FullName == $repData[$c]['ceo'] is true and $groups becomes [13]. In the next line, there are two choices:
either a person is a director (AND a CEO, but it doesn't matter, see why below)
or a person is not a director (could be a CEO)
In both cases, $groups will either get a value of [10] or [5], meaning that no matter what happened inside the statement above, this statement will overwrite it. Thus, only your last if statement is able to produce results you might expect.
"Only one group per role"
In that case a simple switch/case statement will work:
switch($FullName){
case ($repData[$c]['ceo']):
$groups = '[13]';
break;
case ($repData[$c]['director']):
$groups = '[10]';
break;
// etc... for other roles
default:
$groups = '[5]';
break;
}
Or you can go even simpler and use an associative array to combine roles with group numbers. For example:
$roleGroups = array('ceo' => '[13]', 'director' => '[15]', etc);
Then simply see if there's a match:
$groups = '[5]'; // default, to be overwritten if a role is found below
foreach ($roleGroups as $role => $group) { // go through all the groups
if ($FullName == $repData[$c][$role]) { // see if there's a match
$groups = $group; // if so, assign the group
}
}
Hope this makes sense. Either way, $groups will have the number of the role if role is found, 5 otherwise.
I am trying to GET different rows from different columns in php/mysql, and pack them into an array. I am able to successfully GET a jason encoded array back IF all values in the GET string match. However, if there is no match, the code echos 'no match', and without the array. I know this is because of the way my code is formatted. What I would like help figuring out, is how to format my code so that it just displays "null" in the array for the match it couldn't find.
Here is my code:
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode($fbaddra);
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['addr'];
} else {
$fbaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['addr'];
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
UPDATE: The GET Request
I would like the GET request below to return the full array, with whatever value that didn't match as 'null' inside the array.
domain.com/api/core/engine.php?a=fbaddra&facebook=username&facebookp=pagename
The GET above currently returns null.
Requests that work:
domain.com/api/core/engine.php?a=fbaddra&facebook=username or domain.com/api/core/engine.php?a=fbaddra&facebookp=pagename
These requests return the full array with the values that match, or null for the values that don't.
TL;DR
I need assistance figuring out how to format code to give back the full array with a value of 'null' for no match found in a row.
rather than assigning as 'null' assign null. Your full code as follows :
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode('no match');
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
You can even leave else part altogether.
Check your code in this fragment you not use same names for variables:
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = 'null';
}
$fbaddr not is same as $fpaddr, this assign wrong result to if statement.
It was the mysql query that was the problem.
For those who come across this, and need something similar, you'll need to format your query like this:
** MYSQL QUERY **
if ($_GET['PUTVALUEHERE']) {
$g = $_GET['PUTVALUEHERE'];
$gq = $mysqli->real_escape_string($g);
$q1 = "SELECT * FROM `addrbook` WHERE `facebookp` = '".$gq."' OR `facebook` = '".$gq."'";
}
** PHP CODE **
if($_GET['PUTVALUEHERE']{
echo json_encode($row['addr']);
}
I am trying to convert this script over from finding one set of variables eg(playtime_forever) to finding another variable eg(backpack_value)
if (!empty($data->response->games)) {
foreach ($data->response->games as $game) {
if ($game->appid == $game_id) {
$playtime = $game->playtime_forever;
if (($playtime < 5940) && ($playtime > 1)) {
$fh = fopen("final.".$timestamp.".txt", 'a') or die("Can't open file");
...
The page it originally parsed looked like this
http://pastebin.com/rnnCsijd
but will now be this. Pulled from here
http://backpack.tf/api/IGetUsers/v2/?&steamids=76561197992146126&format=json%27;
{
"response": {
"success": 1,
"current_time": 1369669066,
"players": {
"0": {
"steamid": "76561197992146126",
"success": 1,
"backpack_value": 36412.71,
"backpack_update": 1369630863,
"name": ":HIT: Bobo the Monkey Boy",
"notifications": 0
}
}
}
}
A small change but I am unable to make the script do what I want. If you could explain how to go about this and the steps behind it, it would be great. I have been trying for a while but I am unable to finish the script
To get the profiles as per your comment, use this code:
$profiles = array(); //init array so we can use $profiles[] later
$limitValue = 1000; //Limit value of backpack_value
foreach($data->response->players as $player) { // Loop thrugh all the players
if ($player->backpack_value < $limitValue) { // Check the backpack_value
$profiles[] = $player; // Assign the required players to a new array
}
}
var_dump($profiles); // Dump the array to browser for debugning