简体   繁体   中英

PHP, checking data exist or not from webserver API

I given an API LINK and some php codes to my html page. The html page contains information that user input that stored in a database. The API link that sent to my html is a link that look like this "https://nex.web.id/-------/all.php?q=4" and it cotains JSON of user input. From the server side, the server side do the total and percentage calculation and then send it to client side which is what i'm working on right now, i just need to do something like showing the number. The problem is, some users might not choose a certain option at all (eg All users are Male ) then the not choosen option doesn't appear at the JSON as "total": "0", "percentage": "0" . Now what i have to do is check if a data/field doesn't exist, it will show total of 0 and percentage of 0.

Here is the JSON snippet looks like from the API LINK:

 [ { "qno": "5", "qdesc": "Male", "total": "10 Person", "percentage": "100%" } ] 

In that case, every respondences are male, the total and percentage of female should be 0 (it doens't exist/stored). Here is the html form snippet:

 <form action="http://api.nex.web.id/xxxx/all.php" method="post" target="" id="surveyForm"> <label>5. Gender</label> <br> <input type="radio" name="p5" value="Male"> Male <br> <input type="radio" name="p5" value="Female"> Female <br> <br> <button type="submit">click</button> 

And the page for showing result snippet:

 <?php function get_data($url) { $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $data = curl_exec($ch); curl_close($ch); return $data; } $data=get_data('https://nex.web.id/xxxxx/all.php?q=4'); $dt=json_decode($data); //echo $data; ?> <label>5. Gender</label> <br> <h4> Male <?php echo $dt[0]->total;?> ( <?php echo $dt[0]->percentage;?>)</h4> <h4> Female <?php echo $dt[1]->total;?> ( <?php echo $dt[1]->percentage;?>)</h4> <!--check and show 0 and 0% if doensn't exist--> <br> 

Can anyone help me figure this out, please? please let me know if more snippets are needed.

Sorry for my bad english, i'm really need to solve this problem very soon.

As I understand the question the JSON array returned from the API may contain one element (eg just for mail) or two elements (for male and female).

Just accessing the 1st or 2nd element and assuming it contains the data for male / female may not work. (see echo $dt[1]->total; )

Instead I recommend to go through each element of the $dt array (eg with a for each loop), check for the value of the qdesc property, and fill a 2nd array accordingly. Then use that 2nd array for the output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM