在 PHP 上获取未定义索引 foreach each

Getting Undefined index on PHP foreach each

我有一大块 PHP 代码给我未定义的索引消息。

$order = explode(',', $ass_icon_order);

foreach($order as $function){
    $function = (isset($function) ? $function : null);
    if($function != ''){
        $css .= '.ass-sortable-li.li-'.$function.' a:hover, .ass-sortable-li.li-'.$function.'.active a { background:'.$colors[$function].' }';
        ?>
        <li id="<?php echo $function; ?>" rel="<?php echo $function; ?>" class="ass-sortable-li li-<?php echo $function; ?>">
            <?php echo '<a href="#" class="icon-bg"><i class="ass-'.$function.'"></i></a>'; ?>
        </li>
    <?php
        $count_networks++;
    }
}

当我 运行 a print_r($order) 我得到这个数组:

Array
(
    [0] => twitter
    [1] => facebook
    [2] => googleplus
    [3] => delicious
    [4] => stumbleupon
    [5] => pinterest
    [6] => linkedin
    [7] => youtube
    [8] => fblike
    [9] => fbshare
    [10] => fbtalk
    [11] => twitter_followers
    [12] => twitter_following
    [13] => twitter_tweets
    [14] => twitter_shares
    [15] => google_shares
    [16] => google_followers
    [17] => linkedin_shares
    [18] => linkedin_followers
    [19] => delicious_shares
    [20] => delicious_followers
    [21] => youtube_subscribers
    [22] => youtube_views
    [23] => dribbble
    [24] => soundcloud_followers
    [25] => soundcloud_plays
    [26] => instagram
    [27] => mailchimp
    [28] => foursquare
)

当我 运行 print_r($colors) 我得到:

Array
(
    [fblike] => #3b5998
    [fbshare] => #3b5998
    [fbtalk] => #3b5998
    [twitter_followers] => #4ec2dc
    [twitter_following] => #4ec2dc
    [twitter_tweets] => #4ec2dc
    [twitter_shares] => #4ec2dc
    [google_shares] => #2d2d2d
    [google_followers] => #2d2d2d
    [linkedin_shares] => #006da7
    [linkedin_followers] => #006da7
    [delicious_shares] => #3271cb
    [delicious_followers] => #3271cb
    [stumbleupon] => #eb4924
    [youtube_subscribers] => #df1f1C
    [youtube_views] => #df1f1C
    [dribbble] => #f175a8
    [soundcloud_followers] => #ff4c00
    [soundcloud_plays] => #ff4c00
    [instagram] => #3b6a91
    [mailchimp] => #2C9AB7
    [foursquare] => #0732a2
    [pinterest] => #d01d15
)

我似乎从这段代码中得到了通知:

$css .= $colors[$function];

我试过添加 isset,但我认为我没有正确地进行检查。

任何帮助将不胜感激,谢谢

你必须改变这个:

(因为NULL和空串不一样)

$function = (isset($function) ? $function : null);

对此:

$function = (isset($function) ? $function : "");
                                          //^^ See here

此外,您还必须将 if 语句更改为此,以便检查数组中是否存在键:

if($function != '' && in_array($function, array_flip($colors))) {
                    //^^^^^^^^ Check if '$function' exists in the array as key