Notice: Undefined index backdrop_path - php

i want display the backdrop_path of the movie but i get this error
Notice: Undefined index: backdrop_path in /..../public_html/movie.php on line 167
I have added
print_r($tmdbResult);
to see the content of $tmdbResult. I want to display just backdrop_path.
Array
(
[movie_results] => Array
(
[0] => Array
(
[adult] =>
[backdrop_path] => /mbA7SCtJoFTactP1lDHA055qCf.jpg
[genre_ids] => Array
(
[0] => 35
[1] => 28
)
[id] => 261392
[original_language] => en
[original_title] => American Ultra
[overview] => A stoner and his girlfriend's sleepy, small-town existence is disrupted when his past comes back to haunt him in the form of a government operation set to wipe him out.
[release_date] => 2015-08-21
[poster_path] => /6oGHH27nqaLGfpcgYRIZYSJs7AD.jpg
[popularity] => 3.509263
[title] => American Ultra
[video] =>
[vote_average] => 5.6
[vote_count] => 134
)
)
[person_results] => Array
(
)
[tv_results] => Array
(
)
[tv_episode_results] => Array
(
)
[tv_season_results] => Array
(
)
)
The code i use is
ini_set("display_errors",1);
$tmdbResponse = curl_exec($ch);
curl_close($ch);
$tmdbResult = json_decode($tmdbResponse, true );
$backdrop_path = $tmdbResult['movie_results']['backdrop_path'];
$smarty->assign("backdrop_path",$backdrop_path);
print_r($tmdbResult);

The reason is you're getting a numeric index, because the result can contain multiple movies. In this case you're getting just one.
All you need to do is access the array like this #u_mulder said:
$bp = $tmdbResult['movie_results'][0]['backdrop_path'];
The [0] meaning that in case you get multiple results, just need to change that index to access the others. May be you shoulds think of a foreach loop, unless for some reason of yours, you KNOW you'll always get ONE single movie, in that case, hardcode your $bp = $tmdbResult['movie_results'][0]['backdrop_path']; no problem.

Related

Get session values with the same index tag and select the bigger int value

I have a session variable called $_SESSION["shopping_cart"] which saves an array formed by user defined selections on a web page (meaning: products, codes, prices, descriptions and number of active months).
The array will look something like "Array => Array1["xxx"]=> ['product'] = "xxx", ['detail'] = "xxxxx", ['price'] = "xxx", ['envios'] = "x", Array2 => ...... and goes on. Now, SOME of the arrays in there will have an index ['envios'] = "x" and some of them won't. This specific index is always an INT value between 1-12. I need to select all of the values with a index ['envios'] and then save the bigger one of them in a separated variable $corval.
Is there any way to do that?
I found several session functions as session_search() or session_value() BUT all of them will return the value of the index when the input is equal to some array value. And I need to do it the other way around.
Long story short, I need to get all the values for the index ['envios'] inside the session array and save only the bigger of them into a different variable in php. If there is no ['envios'] index the the variable will be equal to 1.
This is the actual array data:
Array ( [BTWL001] => Array ( [name] => P�lulas Winky Lux [code] => BTWL001 [price] => 95.00 [quantity] => 1 [stock] => 8 [image] => /bubale/img/productimg/set5winki.jpg ) [PB001] =>
Array ( [name] => BOLSINHA UNICA [code] => PB001 [price] => 130.00 [quantity] => 1 [stock] => 9999 [image] => /bubale/img/1month.png [envios] => 1 ) [PB003] =>
Array ( [name] => PLANO TRIMESTRAL [code] => PB003 [price] => 300.00 [quantity] => 1 [stock] => 9999 [image] => /bubale/img/3month.png [envios] => 3 ) [PB012] =>
Array ( [name] => PLANO ANUAL [code] => PB012 [price] => 1080.00 [quantity] => 1 [stock] => 9999 [image] => /bubale/img/12month.png [envios] => 12 ) )
Note that there are 3 arrays with the index tag ['envios']. This array is stored in a session so I need to get only those "['envios']" values.
well, after a lot of research I found a solution to this problem, so for those in search of something like this, here we go:
$col = $_SESSION['your session variable'];
$env = array_column($col, 'name of the index you need to extract');
// here the $env will have a new array with only the values identified with the index you looked up for) //
$final = max($env);
//you saved the maximum value of the array//

Looping though arrays dealing with null values

I have an array myArray
Array ([0] =>(
Number => 02348
Food => Array (
[0] => orange
[1] => apple
[2] => plum )
State => Array (
[0] => california
[1] => texas
[2] => arizona )
Status => good )
[1] =>(
Number => 34
Food => Array (
[0] => grape
[1] => bannana
[2] => tomato )
Status => rotten )
[2] =>(
Number => 007
Food => Array (
[0] => oranges
[1] => apples
[2] => plums )
State => Array (
[0] => ohio
[1] => utah
[2] => vermont )
Status => good )
I am looping though my array and then grabbing the fields i need.
for($index=0; $index < count($myArray); $index++){
$food = array_values(array_filter($myArray[$index]["Food"]));
$states = array_values(array_filter($myArray[$index]["State"]));
For the $states line i get an error of
Notice: Undefined index: State
Warning: array_filter() expects parameter 1 to be array, null given
As you can see in my array State may not always be present, is there a way to get around this. Also there is a large amount of data is being pulled dynamically and it would be difficult to change the structure of the array.
How can i loop though my array ignoring nulls but still keeping the place of State. For example
State => Array (
[0] => ohio
[1] => utah
[2] => vermont )
would still be mapped to the [2], and not shifted to [1].
$states = array_values(array_filter($myArray[$index]["State"]));
Using the above example from your code, the array_filter function expects an array so you will need to check that the variable $myArray[$index]["State"] passed to the function is both set and also an array. This will remove the notices and warnings.
You can test for an array using the is_array() function and test if a variable is set using the isset() function.
In this example, an intermediate variable $states_array is set using data from your array. It checks if the original variable is valid, otherwise, it is set to an empty array. This is then passed into the array_filter function.
$states_array = (isset($myArray[$index]["State"]) && is_array($myArray[$index]["State"])) ? $myArray[$index]["State"] : array() ;
$states = array_values(array_filter($states_array));
You may also be interested to know that PHP 7 provides a null coalesce operator which may be helpful when handling variables that may or may not be set.
See:
http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op
https://lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator

Array values to strings

i am trying to get array values to string, but i fail
My array ($epg) looks like this:
Array
(
)
Array
(
[0] => Array
(
[title] => VGhlIEZhbnRhc3kgRm9vdGJhbGwgQ2x1Yg==
[lang] => en
[start] => 1425385800
[end] => 1425387600
[description] => Sm9obiBGZW5kbGV5IGFuZCBQYXVsIE1lcnNvbiBwcmVzZW50IGEgZGlzY3Vzc2lvbiBvbiBrZXkgZmFudGFzeSBmb290YmFsbCBpc3N1ZXMsIGFzIHdlbGwgYXMgdGhlIHdlZWtlbmQncyBQcmVtaWVyIExlYWd1ZSBtYXRjaGVzLiBBbHNvIGZlYXR1cmluZyBndWVzdHMgZnJvbSB0aGUgd29ybGRzIG9mIHNwb3J0IGFuZCBzaG93Yml6Lg==
)
[1] => Array
(
[title] => QmFyY2xheXMgUHJlbWllciBMZWFndWUgUmV2aWV3
[lang] => en
[start] => 1425387600
[end] => 1425391200
[description] => QSBsb29rIGJhY2sgYXQgcmVjZW50IGZpeHR1cmVzIGluIHRoZSBFbmdsaXNoIFByZW1pZXIgTGVhZ3VlLCBhcyB0aGUgc2Vhc29uIGNvbnRpbnVlZCB3aXRoIG1hdGNoZXMgYWZmZWN0aW5nIGJvdGggZW5kcyBvZiB0aGUgdGFibGUu
)
)
Array
(
)
And then i create foreach loop, and try to get values like this:
$title = $epg['title'];
$lang = $epg['lang'];
echo $lang;
echo $title;
But i get errors:
Notice: Undefined index: title in........ Notice: Undefined index:
lang in.........
I am guessing that happens, because i have strange array , these empty arrays at start and end.
If so, how can i fix it?
Regards
M
When you define the array like here
[0] => Array
(
[title] => VGhlIEZhbnRhc3kgRm9vdGJhbGwgQ2x1Yg==
[lang] => en
[start] => 1425385800
[end] => 1425387600
[description] => Sm9obiBGZW5k...
)
If you don't have title, lang, etc. delcared as variables you need to have
[0] => Array
(
['title'] => VGhlIEZhbnRhc3kgRm9vdGJhbGwgQ2x1Yg==
['lang'] => en
['start'] => 1425385800
['end'] => 1425387600
['description'] => Sm9obiBGZW5k...
)
Use this remove ur empty and then use this
print_r(array_filter($epg));
echo $title = $epg['title']
Check if your array is not empty
if (count($epg) != 0)
You get notices, not errors. But it is good practice to treat them as errors and removing from Your code.
These notices are about undefined indexes, so You have to check if given index is present in current element of array. You can do it like this:
$title = array_key_exists('title',$epg) ? $epg['title'] : NULL;
Manual

Insert array in to MySQL with PHP

I am trying to insert an array in to MySQL using PHP. I followed the excellent advice given on here to use the implode command and it worked great for one array, but this one seems to be dying. This array is slightly different than the other, but I don't know how to explain the difference.
Here is my code:
$sql = array();
foreach( $ride_detail as $row ) {
$sql[] = '('.$row['id'].', "'.mysql_real_escape_string($row['name']).'",
"'.$row['version'].'")';
}
mysql_query('INSERT IGNORE INTO ride (ride_id, name, version) VALUES '.implode(',', $sql));
I'm getting this message over and over again.
Warning: Illegal string offset 'id' in ride_details.php on line 60
Warning: Illegal string offset 'name' in ride_details.php on line 60
Warning: Illegal string offset 'version' in ride_details.php on line 61
The content of my array (using print_r) is:
Array ( [id] => 21570117 [name] => Night ride home from work [start_date_local] => 1347302039 [elapsed_time] => 53:56 [moving_time] => 52:04 [distance] => 12.6 >>[average_speed] => 14.5 [elevation_gain] => 474 [location] => Englewood, CO [start_latlng] => Array ( [0] => 39.547792011872 [1] => -104.86300536431 ) [end_latlng] => Array ( [0] => 39.655485888943 [1] => -104.88656991161 ) [version] => 1355428869 [athlete] => Array ( >>[id] => 832001 [name] => Bob Kratchet [username] => bob_kratchet ) [bike] => Array ( [id] => 281303 [name] => Giant Allegre commuter ) [maximum_speed] => 29.3 [calories] => 372 >[average_power] => 107 [commute] => 1 )
I am a complete noob...
Since your $ride_detail is just one array, $row is 21570117 (integer), Night ride home from work (string), and so on, one by one. The code then attempts to get the id key of each element, then the name key, and so on, generating a [expletive]-ton of error messages as it goes.
It looks like you're intending to have $ride_detail be an array of arrays, or you don't actually want a foreach loop at all.
try this
foreach( $ride_detail as $row ) {
$sql = array( $row['id'], mysql_real_escape_string($row['name']), $row['version']) ;
}
mysql_query('INSERT IGNORE INTO ride (ride_id, name, version) VALUES ($sql[0] ,$sql[1] , $sql[2] ) ');

foreach loops & stdclass objects

I've seen similar questions on here but I can't seem to apply the solutions to my problem. I have a variable called $results which I got from an API. I'll change the proper nouns so as to protect my work's customers:
stdClass Object
(
[out] => stdClass Object
(
[count] => 2
[transactions] => stdClass Object
(
[RealTimeCommissionDataV2] => Array
(
[0] => stdClass Object
(
[adId] => 12345678
[advertiserId] => 123456789
[advertiserName] => Chuck E. Cheese, inc.
[commissionAmount] => 50
[country] => US
[details] => stdClass Object
(
)
[eventDate] => 2009-11-16T09:44:25-08:00
[orderId] => X-XXXXXXXXXX
[saleAmount] => 0
[sid] => 123456789
[websiteId] => 2211944
)
[1] => stdClass Object
(
[adId] => 987654321
[advertiserId] => 12345
[advertiserName] => Chorizon Wireless.
[commissionAmount] => 50
[country] => US
[details] => stdClass Object
(
)
[eventDate] => 2009-11-16T09:58:40-08:00
[orderId] => X-CXXXXXX
[saleAmount] => 0
[sid] => 61-122112
[websiteId] => 1111922
)
)
)
)
)
I shortened it to two entries here but the number of entries will vary, it's the result of a check for transactions in the past hour, there may sometimes be only one and sometimes as many as a dozen.
I want to assign these entries to variables like websiteId1 websiteId2 etc. I know I need to do a foreach loop but can't seem to figure it out. How can I write it so that I get the "[details]" as well?
foreach ($results->out->transactions->RealTimeCommissionDataV2 AS $commissionData) {
// you can access the commissionData objects now, i.e.:
$commissionData->adId;
$commissionData->details;
}
<?
foreach ($result->out->transactions->RealTimeCommissionDataV2 as $item)
{
// do somthing with each item.
print_r($item);
// or the details array
$num_details = sizeof($item->details)
}
I think this is what you want.
EDIT
Updated based on some notes in the documentation. Specifically, these two
a numerically indexed array will not
produce results unless you use
EXTR_PREFIX_ALL or
EXTR_PREFIX_INVALID.
Prefixes are automatically separated
from the array key by an underscore
character.
echo extract( $results->out->transactions->RealTimeCommissionDataV2, EXTR_PREFIX_ALL, 'websiteId' );
// test the extract
print_r( $websiteId_0 );

Categories