differentiating between two different JSON objects using php - php

I'am creating a search engine.In this search engine we search movies by actor's name . Searching movies through actor's name returns two different types of JSON data . If the actor name is not found then the JSON is returned in the following format (see the http://netflixroulette.net/api/api.php?actor=)
{"errorcode":404,"message":"Sorry! We couldn't find any movies with that actor!"}
and when the actor name is found the JSON returned is multidimensional and is in the following format.(see the link:http://netflixroulette.net/api/api.php?actor=Yuki%20Kaji)
[{"unit":883,"show_id":70299043,"show_title":"Attack on Titan","release_year":"2013","rating":"4.6","category":"Anime","show_cast":"Yuki Kaji, Yui Ishikawa, Marina Inoue, Daisuke Ono, Hiro Shimono, Hiroshi Kamiya, Keiji Fujiwara, Kish\u00f4 Taniyama, Romi Park, Ryota Ohsaka","director":"","summary":"For over a century, people have been living behind barricades to block out the giant Titans that threaten to destroy the human race. When a Titan destroys his hometown, young Eren Yeager becomes determined to fight back.","poster":"http:\/\/netflixroulette.net\/api\/posters\/70299043.jpg","mediatype":1,"runtime":"24 min"}, { "unit":17256,"show_id":80009097,"show_title":"Magi","release_year":"2012","rating":"3.8","category":"TV Shows","show_cast":"Kaori Ishihara, Erica Mendez, Yuki Kaji, Erik Scott Kimerer, Haruka Tomatsu, Cristina Valenzuela, Daisuke Ono, Matthew Mercer, Takahiro Sakurai, Lucien Dodge","director":"","summary":"A land of mysterious ruins and a magical treasure hunt await young Aladdin and his courageous friend Alibaba for the adventure of their lives.","poster":"http:\/\/netflixroulette.net\/api\/posters\/80009097.jpg","mediatype":0,"runtime":"N\/A"}]
I've tried this code
$output = json_decode($output);
if($output['errorcode']==400)
{
foreach($output as $key =>$row)
{
echo "<p>$key : $row";
echo '<br>';
}
}
else
{
foreach($output as $value)
{
foreach($value as $key =>$row)
{
if($key == "mediatype" || $key == "runtime" || $key == "unit" || $key == "show_id" )
continue;
else if($key == "show_cast" )
{
echo"<br>Show Cast:";
$pieces = explode(",", $row);
foreach($pieces as $strings)
{
$link='http://localhost:8000/?Title=&director=&Actor='.$strings;
echo "<li><a href='$link'>$strings</a>";
}
echo "<br>";
}
else if($key == "director" )
{
if(empty($row))
echo"<br>Director:No details of director<br>";
else
{
echo"<br>Director:";
$link='http://localhost:8000/?Title=&director='.$row.'&Actor=';
echo "<a href='$link'>$row</a><br>";
}
}
else if($key !="poster")
{
echo "$key : $row";
echo '<br>';
}
else
{
echo '<img src="'.$row.'" />';
}
}
echo "<br><br><br><br><br><br>";
}
}
Using this gives me error of "Undefined index: errorcode" . Basically my question is what to use in if-else condition to differentiate between the two received JSON objects that are recieved.
Please help!! Thanks in advance..

Try if(is_object($output) && isset($output->errorcode)).
So it would be like this:
$output = json_decode($output);
if(is_object($output) && isset($output->errorcode))
{
foreach($output as $key =>$row)
{
echo "<p>$key : $row";
echo '<br>';
}
}
else
{
// the rest
}
What's happening is the json is an object when there are no matches, but it is an array of objects when there are matches.
If we just use if(isset($output->errorcode)), then, in the case where there are matches, $output is an array and not an object, and the above attempts to treat it like an object, resulting in an alert about treating an array like an object.
The boolean && will "short circuit" when the first condition is false, and it will never evaluate the second condition. So we first check to see if it is an object with is_object().. if it isn't, then it will never check to see if it has a member called "errorcode", dodging the alert about treating an array as an object.

Related

If condition equal to array value

I have an array. Inside that array my Fruit_Name could either be Pear or Apple depending on the button i select in the previous page. Lets say i select Apple the if statement does not seem to work however it does echo. It echos$FruitType and it seems to get Apple which should fire up my if statement and show me "You did it!", but my if condition doesn't. What am i doing wrong?
Array
Fruit_Name=Apple
My Function
function GetField($arr, $field)
{
$result = ' ';
foreach($arr as $line)
{
if (explode('=', $line) [0] == $field)
{
$result = explode('=', $line) [1];
}
}
return $result;
}
$FruitType= GetField($array, 'Fruit_Name');
echo $FruitType;
if ($FruitType == "Apple")
{
echo "You did it!";
}
else if ($FruitType == "Pear")
{
echo "Its not Pear!";
}
When comparing strings (and really, you should do this with any data type) in php, you must use the === notation. The == is only used for numbers, and when used on strings leads to problems like the one you're facing.
So your code should be
If ( $FruitType === "Apple" )
And the Getfield function is incorrect, as mentioned and explained by Dagon.

Parsing decoded JSON in PHP

I have managed to decode some JSON in PHP successfully (not as painful as I thought), but it's been such a long time since I've done any real PHP, my brain has drawn a blank on the following.
The decoded json looks like this
[Array]
item {
[0]
{
[live]=>
[name]=>Paul
[value]=>10
}
[1]
{
[live]=>1
[name]=>Fred
[value]=>32
}
and so on
The problem I'm having is this - I'm trying to iterate through the structure to test first if live==1 and then if it's the first live name, to output it as a selected value to a HTML drop down.
I'm currently trying like this
$t = 0;
$count = 0;
foreach($decode['items'] as $option=>$value)
{
print_r("option = $option\n");
if ($option=>isLive == 1)
{
print_r("isLive is true for $option[$count]['names']\n");
if ($t == 0)
{
echo "<option value=$option[name] selected>$value[name]</option>";
$t = 1;
}
else
echo "<option value=$option[name]>$value[name]</option>";
}
else
{
print_r("isLive is false for $option[$count]=>name\n");
}
$count++;
}
the problem is that I don't seem to be able to get the if statement correct for this to work. This is probably a seriously simple problem and will no doubt make me face palm, but I could do with a pointer in the right direction here!
If the json is like you showed us you could not iterate over anything with your foreach because your array does not contain a key named items.
Using the provided structure this should do the trick:
foreach($decode["item"] as $item) {
if($item->live == 1) {
...
} else {
...
}
}
If $item is not an object use $item['live'] instead.
P.S.: You should really turn error_reporting on. $option=>isLive is no valid syntax.
$t = 0;
$count = 0;
$arr = json_decode($json,true);
foreach($arr as $key=>$val)
{
print_r($key);
if($val['live'])
{
if($t == 0)
{
echo '<option value='.$val['name'].' selected>'.$val['name'].'</option>';
$t = 1;
}
else
{
echo '<option value='.$val['name'].'>'.$val['name'].'</option>';
}
}
else
{
echo $key.' not printed cause it hasn\'t live set to true';
}
$count++;
}

Delete element from array if not found

I have some code I created which is supposed to see if something exists in an array of strings. If it does not exist, I want to delete that element of the array. I thought we do this with unset, but it doesnt seem to be working. Mind helping?
echo '<br>size of $games before end-check: '.sizeof($games);
foreach ($games as $game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
}
else {
echo "<br>end of game not found. incomplete game";
unset($game);
}
}
echo '<br>size of $games after end-check: '.sizeof($games);
output:
size of $games before end-check: 2
end of game found
end of game not found. incomplete game
size of $games after end-check: 2
Because you unset the variable $game, not the element in the array. Try this:
echo '<br>size of $games before end-check: '.sizeof($games);
foreach ($games as $index => $game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
}
else {
echo "<br>end of game not found. incomplete game";
unset($games[$index]);
}
}
echo '<br>size of $games after end-check: '.sizeof($games);
You have to unset the index of game.
foreach ($games as $key => $value) {
// all your logic here, performed on $value
unset($games[$key]);
}
This merely unsets your local reference to the element. You need to be referring directly to the array.
foreach($games as $key => $game)
unset($games[$key]);
That won't work: foreach creates a new variable, copying the old one. Unsetting it will do nothing to the original value. Likewise, making it a reference won't work either, since only the reference would be deleted.
The nicest way to do this would be with array_filter:
$games = array_filter($games, function($game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
return true;
}
else {
echo "<br>end of game not found. incomplete game";
return false;
}
});
This uses the anonymous function syntax introduced in PHP 5.3. If the function returns true, the element is kept; if it returns false, the element is removed.
You can also call by reference:
foreach($games as &$game) {
unset($game);
}
In this way you can also change $game (eg. $game .= " blah";) and the original array will be modified.
You can use array_splice in conjunction with an incrementally-increasing index variable to remove the current item from the array:
$index = 0;
foreach ($games as $game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
}
else {
echo "<br>end of game not found. incomplete game";
array_splice($games, $index, 1);
}
$index++;
}

PHP If statements and Arrays

I have an array
$results = array(101, 102, 103, 104, 105)
I also have a input field where the user enters a number
<input type ="text" name="invoice" />
I put what the number that user enters in, into a variable
$id = $_POST['invoice']
How would I write an if statement to check to see if the number that user entered is in that array
I have tried doing in a for each loop
foreach($result as $value){
if($value == $id){
echo 'this';
}else{
continue;
}
is there a better way of doing this?
if (in_array($id, $results)) {
// ...
}
http://php.net/manual/en/function.in-array.php
Use in_array():
if (in_array($_POST['invoice'], $your_array)) {
... it's present
}
ok you can try this:
if ( in_array($id, $results))
{
// execute success
}
else
{
// execute fail
}
You can use in_array, like the others have suggested
if(in_array($id,$results)) {
//do something
} else {
$no_invoice = true;
}
but if you happen to want to use your array key for anything, you can kill two birds with one stone.
if($key = array_search($id,$results,true)) {
echo 'You chose ' . $results[$key] . '<br />';
}
Obviously for echoing you don't need my method - you could just echo $id - but it's useful for other stuff. Like maybe if you had a multi-dimensional array and element [0]'s elements matched up with element[1]'s elements.
If you are looking to compare values of one array with values of another array in sequence then my code is really simple: check this out it will work like this:
if (1st value of array-1 is equal to 1st value of array-2) { $res=$res+5}
if($_POST){
$res=0;
$r=$_POST['Radio1']; //array-1
$anr=$_POST['answer']; //array-2
$arr=count($r);
for($ac=0; $ac<$arr; $ac++){
if($r[$ac]==$anr[$ac]){
$res=$res+5;
}
}
echo $res;
}
Not quite.
your way is good enough, it only needs to be corrected.
foreach($results as $value){
if($value == $id){
echo 'this';
break;
}
}
is what you really wanted

PHP Array foreach question

I have a question about arrays and foreach.
If i have an array like this:
$test_arr = array();
$test_arr['name1'] = "an example sentence";
$test_arr['anything'] = "dsfasfasgsdfg";
$test_arr['code'] = "4334refwewe";
$test_arr['empty1'] = "";
$test_arr['3242'] = "";
how can I do a foreach and "pick" only the ones that have values? (in my array example, would only take the first 3 ones, name1, anything and code).
I tried with
foreach ($test_arr as $test) {
if (strlen($test >= 1)) {
echo $test . "<br>";
}
}
but it doesn't work. Without the "if" condition it works, but empty array values are taken into consideration and I don't want that (because I need to do a <br> after each value and I don't want a <br> if there is no value)
Sorry if I don't explain myself very well, I hope you understand my point. Shouldn't be too difficult I guess..
Thanks for your help !
Maybe will work
foreach ($test_arr as $test) {
if (strlen($test)!=="") {
echo $test . "<br>";
}
}
Your solution with corrected syntax:
foreach ($test_arr as $test) {
if (strlen($test)>=1) {
echo $test . "<br>";
}
}
Since empty strings are false, you could just do this (but you'd exclude 0's with the if):
foreach ($test_arr as $key => $val) {
if ($val) {
echo $val. "<br>";
}
}
If it has to be an empty string then (excluding 0 and FALSE):
foreach ($test_arr as $key => $val) {
// the extra = means that this will only return true for strings.
if ($val !== '' ) {
echo $val. "<br>";
}
}
Since it looks like you're using an associative array, you should be able to do this:
foreach( $test_arr as $key => $value )
{
if( $value != "" )
{
echo $value . "<br />";
}
}
As shown, you can test $value for an empty string directly. Since this is precisely the test you are trying to accomplish, I would hope that this would solve your problem perfectly.
On another note, this is pretty straight forward and should be very maintainable in the future when you've forgotten exactly what it was that you were doing!
You are better off to use a while loop like this:
while(list($test_key, $test_value) = each($test_arr))
{
if($test_value != "") { echo $test_value . "<br/>"; }
}
reset($test_arr);
If your array gets large, the while will be much faster. Even on small arrays, I have noticed a big difference in the execution time.
And if you really don't want the array key. You can just do this:
while(list(, $test_value) = each($test_arr))
{
if($test_value != "") { echo $test_value . "<br/>"; }
}
reset($test_arr);
You can check if the value is emtpy with empty().
Note that values like 0 or false are considered empty as well, so you might have to check for string length instead.
just a simple typing error:
foreach ($test_arr as $test) {
if (strlen($test) >= 1) {
echo $test . "<br>";
}
}
Try this:
foreach ($test_arr as $test) {
if (strlen($test) > 0) {
echo $test . "<br>";
}
}

Categories