PHP:具有空值的数组在foreach中给出错误

伊森·奥沙利文(Ethan O'Sullivan)

对于此示例,当我调用变量时$my_settings,输出将如下所示:

Array (
    [personal_options] => Array (
            [rich_editing] => rich_editing
            [admin_color] => admin_color
            [comment_shortcuts] => comment_shortcuts
            [admin_bar_front] => admin_bar_front
        )
    [name] => Array (
            [nickname] => nickname
        )
    [contact_info] => Array (
            [url] => url
        )
    [about_yourself] => Array (
            [description] => description
        )
    [yoast_seo] => 
)

在运行foreach循环时,请获得每个人都喜欢的“为foreach()提供了无效参数”错误,因为此数组具有[yoast_seo] =>,它为空并将其丢弃。

目前,我foreach的设置如下:

$my_settings = get_option( 'dsbl_profile_settings' );

if ( is_array( $my_settings ) || is_object( $my_settings ) ) {
    foreach ( $my_settings as $group => $item ) {
        foreach ( $item as $value ) {
            echo '<pre>'; print_r( $value ); echo '</pre>';
        }
    }
}

如您所见,我已经使用is_array()is_object()在我的循环中签入。我的猜测是,在运行之前,我还需要执行检查以查看其是否为空[yoast_seo] =>自从我在if声明中尝试了以下操作后,我对实现该方法的最佳方法感到茫然

if ( is_array( $profile_fields ) || is_object( $profile_fields ) || isset( $profile_fields ) ) { // Attempt #1

if ( ( is_array( $profile_fields ) || is_object( $profile_fields ) ) && isset( $profile_fields ) ) { // Attempt #2
卡马尔帕尔

这是因为您嵌套了foreach,并且要提供一个空变量,所以在传递之前,应检查该变量是否为数组。

if ( is_array( $my_settings ) || is_object( $my_settings ) ) {
    foreach ( $my_settings as $group => $item ) {
        if(is_array($item)) {
            foreach ( $item as $value ) {
                echo '<pre>'; print_r( $value ); echo '</pre>';
            }
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章