当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Undefined array index

问题描述:

I have the following array structure (from a JavaScript object through JQuery AJAX):

[column_id]

[column_content_id]

[content]

.....

[options]

.....

[styles]

.....

I go through the array with:

foreach($this->rom['columns'] as $column_id => $columns) {

// add columns

$this->add_column($column_id, $this->id, $columns['options']['column-width']);

// content

foreach($columns as $content_id => $content) {

// assign values

$values = array(

'styles' => $content['styles'],

'options' => $content['options'],

'style_class' => 'is-cc-style',

'in_column' => true,

'id' => str_replace('#', '', $mc_content_id),

'column_id' => $column_id,

'content_type' => $content['content_type'],

'options_class' => 'is-cc-option'

);

}

}

Everything works well, except that I receive the following notices:

Notice: Undefined index: styles

Notice: Undefined index: options

Notice: Undefined index: content_type

How can I avoid this? At the moment I use:

if(isset($content['styles'])) {

$content['styles'] = '';

}

But I guess that's not how it's supposed to be.

Thanks for any help! :)

网友答案:

It looks like you want to return an empty string if the property is not set, and what you're using looks exactly like a syntax error to me ?

Here's how I'd do it

    $values = array(
        'styles'        => isset($content['styles']) ? $content['styles'] : "", 
        'options'       => isset($content['options']) ? $content['options'] : "",
        'style_class'   => 'is-cc-style', 
        'in_column'     => true, 
        'id'            => str_replace('#', '', $mc_content_id),
        'column_id'     => $column_id,
        'content_type'  => isset($content['content_type']) ? $content['content_type'] : "",
        'options_class' => 'is-cc-option'
    );
网友答案:

You will get notices like this sometimes in php when you try to assign something that is NULL to a variable (it depends on the type of errors you have turned on), I am guessing that styles, options and or content_type are nullable? If so you can use an @ to suppress the warning like so:

    $values = array(
        'styles'        => @$content['styles'], 
        'options'       => @$content['options']
    );

or if you want to set it to a default value adeneo's solution would be best.

分享给朋友:
您可能感兴趣的文章:
随机阅读: