问题
I want to skip iterate in a php foreach anytime when I receaive "Undifined index". Here is my code so far:
<?php
$albums = $facebook->api("/me/albums");
$i=0;
foreach ($albums['data'] as $album) {
if (is_null($album['cover_photo'])) continue;
if($i==8) break;
$album_id = $album['id'];
$album_cover = $album['cover_photo'];
$album_name = $album['name'];
$album_count = $album['count'];
$covers = $facebook->api("/" . $album_cover . "");
$source = $covers['source'];
?>
If I don't have the if is_null
syntax the code breaks but I receive the error that cover_photo index is undefined (it is the normal behaviour). At least if I could not display the error it could be enough.
回答1:
Instead try,
if (!isset($album['cover_photo'])) continue;
Or better check the variable isset
before assigning it.
$album_cover = (isset($album['cover_photo'])) ? $album['cover_photo'] : '';
来源:https://stackoverflow.com/questions/15884909/php-foreach-skip-iterate-in-an-array