Jump to content

Looping through JSON file to find value


Go to solution Solved by Texan78,

Recommended Posts

Hello, 

 

I have this JSON response that has streamStatus": "false", as one of the variables. There is 6 total entries on this. Here is an example of two. 

{
    "streamers": [
        {
            "DisplayName": "Nick Copeland",
            "StreamKey": "ncopeland",
            "StreamURL": "rtmp://strsvr-01.dfwstormforce.com/live/",
            "gpsStatus": "false",
            "UserLat": "N32.97353",
            "UserLon": "W96.71433",
            "UserHeading": "none",
            "UserLocation": "2 miles NNE of downtown Richardson, Texas",
            "streamStatus": "false",
            "CurrentViewers": 0,
            "TimeStamp": "2016-10-24 11:36:29"
        },
        {
            "DisplayName": "Kevin Saunders",
            "StreamKey": "ksaunders",
            "StreamURL": "rtmp://strsvr-01.dfwstormforce.com/live/",
            "gpsStatus": "false",
            "UserLat": "N30.43435",
            "UserLon": "W87.20219",
            "UserHeading": "none",
            "UserLocation": "",
            "streamStatus": "true",
            "CurrentViewers": 0,
            "TimeStamp": "2016-10-24 11:36:56"
        },

I have a code that works great for a single JSON response but, what I am trying to do is search through the JSON response of that file and if any one of the "streamStatus" is true then show a certain message then show a different message if false. Where I am stuck is I am not sure how to search through them all. 

<?php

$jsonPath = "http://stream.dfwstormforce.com/inc/api.php"; // URL to json data

// Lets get and parse the data and create the variables
  $json_string = file_get_contents($jsonPath);
  $parsed_json = json_decode($json_string, true);
  $status = ($parsed_json['streamers']['streamStatus']) ? 'true' : 'false';
  
  var_dump($status);
  
// Lets assembly the banners to display
$notifyOffline = '<div class="alert alert-danger" role="alert" data-toggle="tooltip" data-placement="top" title=" "> There are currently no active chasers online streaming at this time.</div>';

$notifyOnline = '<div class="alert alert-success" role="alert" data-toggle="tooltip" data-placement="top" title=" "> There are currently X chasers streaming LIVE... </div>';


if ($status == "true") {
    echo $notifyOnline;
} else {
    echo $notifyOffline;
}
?>
Link to comment
https://forums.phpfreaks.com/topic/302399-looping-through-json-file-to-find-value/
Share on other sites

 what I am trying to do is search through the JSON response of that file and if any one of the "streamStatus" is true then show a certain message then show a different message if false. Where I am stuck is I am not sure how to search through them all. 

 

I Also don't need to use the JSON file. If need be I can just create a file that connects to the DB and searches that column to check if any of them are true and if so then echo a certain message. If they are all false then echo a different message. 

@Texan78:

 

I know what you've written. My question is what you don't understand. The data structure? How loops work? How to set a boolean variable?

all_status_false := true   // first assume that all status are false
each stream in json:
  if stream.status != "false":   // found a status which is not "false", change the variable
    all_status_false := false
    break    // if nothing else needs to be done, stop the loop

 

@Texan78:

 

I know what you've written. My question is what you don't understand. The data structure? How loops work? How to set a boolean variable?

all_status_false := true   // first assume that all status are false
each stream in json:
  if stream.status != "false":   // found a status which is not "false", change the variable
    all_status_false := false
    break    // if nothing else needs to be done, stop the loop

 

 

I am not sure if I am understanding your question. I thought I stated what I am having a problem with. I may not be using the correct wording. What I am trying to do is search through the JSON file and if any of the "streamStatus" is true then show a certain message, if false show a different one. 

 

What I am having a problem with is I am not sure how to search through all of the "streamStatus" from the multiple response from the JSON file to check if any of them are true. 

 

Would it be easier if I just connected to the DB and looped through them? If so how would I go about doing that. 

include('dbconn.php');

$sql = "SELECT StreamStatus FROM streamdb";$result = $conn->query($sql);


if ($result->num_rows > 0) {
    // output data of each row
    $i = 1;
    while($row = $result->fetch_assoc()) {
    $status[$i] = $row["StreamStatus"];


    $i++;


    }
} 


// Lets assembly the banners to display
$notifyOffline = '<div class="alert alert-danger" role="alert" data-toggle="tooltip" data-placement="top" title=" "> There are currently no active chasers online streaming at this time.</div>';


$notifyOnline = '<div class="alert alert-success" role="alert" data-toggle="tooltip" data-placement="top" title=" "> There are currently X chasers streaming LIVE... </div>';




if ($status[$i]  == "true") {
    echo $notifyOnline;
} else {
    echo $notifyOffline;
}

So I am approaching this a little different now instead of trying to go through the JSON file I am just query the DB column and creating an array. Now what I am wanting to do is if any of those values are "true" then echo the $notifyOnline message. If they are all false then echo the $notifyOffline message. I am having an issue getting this to work correctly. Any assistance would be greatly appreciated.  

 

Here is what I have come up with as of now. 

$resultArr = array();//to store results
//to execute query
$executingFetchQuery = $mysqli->query("SELECT `StreamStatus` FROM streamdb WHERE 1");
if($executingFetchQuery)
{
   while($arr = $executingFetchQuery->fetch_assoc())
   {
        $resultArr[] = $arr['StreamStatus'];//storing values into an array
   }
}
print_r($resultArr);//print the rows returned by query, containing specified columns

// Lets assembly the banners to display
$notifyOffline = '<div class="alert alert-danger" role="alert" data-toggle="tooltip" data-placement="top" title=" "> There are currently no active chasers online streaming at this time.</div>';

$notifyOnline = '<div class="alert alert-success" role="alert" data-toggle="tooltip" data-placement="top" title=" "> There are currently X chasers streaming LIVE... </div>';


if ($resultArr == "true") {
    echo $notifyOnline;
} else {
    echo $notifyOffline;
}

As you can see from my test URL there is a "true" value in the array therefore it should echo the $notifyOnline message but it isn't. 

 

http://www.mesquiteweather.net/stream/inc/test.php

 

-Thanks

Ok I appear to have this working. Can someone let me know if this logic seems correct?

$resultArr = array();//to store results
//to execute query
$executingFetchQuery = $mysqli->query("SELECT `StreamStatus` FROM streamdb WHERE 1");
if($executingFetchQuery)
{
   while($arr = $executingFetchQuery->fetch_assoc())
   {
        $resultArr[] = $arr['StreamStatus'];//storing values into an array
   }
}

// Lets assembly the banners to display
$notifyOffline = '<div class="alert alert-danger" role="alert" data-toggle="tooltip" data-placement="top" title=" "> There are currently no active chasers online streaming at this time.</div>';

$notifyOnline = '<div class="alert alert-success" role="alert" data-toggle="tooltip" data-placement="top" title=" "> There are currently X chasers streaming LIVE... </div>';


if (in_array("true", $resultArr)) {
    echo $notifyOnline;
} else {
    echo $notifyOffline;
} 

-Thanks!

  • Solution

Thanks, I have already resolved this and it is working like I am wanting it to. It may not be perfect but it does what I need it to. Your solution really doesn't make much sense to me. Not saying it is wrong, just saying I didn't understand what you were doing or where to apply it. This is what I have come up with and it's working fine now in all aspects. 

$resultArr = array();//to store results

//lets execute the query
$executingFetchQuery = $mysqli->query("SELECT `StreamStatus` FROM streamdb WHERE 1");
if($executingFetchQuery)
{
   while($arr = $executingFetchQuery->fetch_assoc())
   {
        $resultArr[] = $arr['StreamStatus'];//storing values into an array
   }
}

$counts = array_count_values($resultArr);//lets count the results
$online = $counts['true'];

// Lets assemble the banners to display
$notifyOffline = '<div class="alert alert-danger" role="alert" data-toggle="tooltip" data-placement="top" title=" "> There are currently no active chasers online streaming at this time.</div>';

$notify1Online = '<div class="alert alert-success" role="alert" data-toggle="tooltip" data-placement="top" title=" "> There is currently 1 chaser streaming LIVE... </div>';

$notifyOnline = '<div class="alert alert-success" role="alert" data-toggle="tooltip" data-placement="top" title=" "> There are currently '.$online.' chasers streaming LIVE... </div>';


//lets display the banners
if ( $online == "1" ) {
    echo $notify1Online;
} elseif ( $online >= "2" ) {
    echo $notifyOnline;
} else {
    echo $notifyOffline;
}
Edited by Texan78

Like I said, this is nonsense. You're circumventing basic database features to implement them yourself in the most cumbersome and inefficient way.

 

I'm not sure why you struggle with my queries, because this is nothing more than plain English and common sense:

variant 1
every status is false means: no record with a true status exists

variant 2
every status is false means: the number of records with a true status is 0

The query immediately yields the result. No need for any loops.

 

You're free to do whatever you want, but if you want to be a programmer, it's a good idea to learn instead of rejecting everything you don't know yet.

it does what I need it to.

 

That is one of the biggest problems with "coders". If you are going to be a programmer, you need to get rid of the "It works so I will use it" mentality.

 

Did you even try to run the queries @Jaques1 provided you?

Edited by benanamen

 

I'm not sure why you struggle with my queries, because this is nothing more than plain English and common sense:

 

 

You're free to do whatever you want, but if you want to be a programmer, it's a good idea to learn instead of rejecting everything you don't know yet.

 

 

It may be common sense for someone who is proficient in PHP but, unlike me I am not therefore it does not make any sense to me. I have no clue where to even insert or how to use the example you posted nor was there any in-depth explanation to learn from. If you want people to learn maybe try better at explaining your solution to those who are not proficient in the PHP programming language instead of talking down to them for not knowing and asking for help as I didn't reject anything, I was just easier to go with what I had already come up with from my other research on the matter than trying to get you to explain it more in-depth in more a understandable way. 

That is one of the biggest problems with "coders". If you are going to be a programmer, you need to get rid of the "It works so I will use it" mentality.

 

Did you even try to run the queries @Jaques1 provided you?

 

 

Like I mentioned above, I have no desire to be a programmer. I dabble here and there with little one off simple tasks when I can't hire someone to do it because my company is cheap and all they care about is that it works. There problem not mine. Considering what I came up with was based off of countless hours of research and trial and error I think that is a little more than what most people do who just want code handed to them for free. No I didn't try them and I outlined above why. 

 

The one thing I have learned over 17yrs dabbling about programming is there is dozens of ways to do something and not everyone is going to agree with everyones methods because it isn't their way of doing it. Maybe even people approached others in a more teaching manner instead of being forceful it might make it easier for others to learn. You want someone to learn, teach them. Don't be forceful and talk down to them. 

 

I have a small task list of things I need done. Care to do them for me or teach me in a more practical way? I would certainly hire someone out of my own pocket if I could find someone. After all, this is a "help" forum. I am pretty sure most people didn't come out of the womb knowing the PHP programming language and since I am not a programming or "coder" and have no desire to be then this is my only option and reason I prefer to hire someone than to get beat down on a forum. 

 

Thanks for your time and effort. I have my solution and if it doesn't work down the road then that won't be my issue. 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.