简体   繁体   English

PHP如何解决非法偏移类型错误?

[英]PHP how to fix Illegal offset type error?

So I have this $_POST which I am trying to check if it is set but when I do that, it gives me the error in the title. 所以我有这个$ _POST,我试图检查它是否已设置,但是当我这样做时,它给我标题中的错误。

The $_POST contains array within array. $ _POST包含数组中的数组。 So that could be the reason. 因此,这可能是原因。 $_POST has value if the checkbox is checked otherwise nothing is posted. 如果选中此复选框,则$ _POST具有值,否则不发布任何内容。

So example of what $_POST would contain: 因此,$ _POST将包含的示例:

array() => 'item-one' => array( 102 ) => 'on'

I am using this in PHP: 我在PHP中使用它:

function testing( $db_id ) {
    $fields = array( 'one', 'two' );

    foreach( $fields as $field ) {
         if ( isset( $_POST['item-' . $field][$db_id] ) ) {
              // do something
         }
    }
}

Thanks for looking. 感谢您的光临。

Try this, 尝试这个,

foreach( $fields as $field ) {
     if (isset($_POST['item-'.$field]) and in_array($db_id,$_POST['item-'.$field])){
          // do something
     }
}

Alternatively you can try it like, 另外,您也可以尝试

$fields=array('item-one','item-two')
foreach( $fields as $key=>$field ) {
     if (isset($_POST[$field]) and in_array($db_id,$_POST[$field])){
          // do something
     }
}

Try with in_array : 尝试使用in_array

$fields = array( 'one', 'two' );

foreach( $fields as $field ) {
     if ( in_array($_POST['item-' . $field][$db_id], $fields) ) {
          // do something
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM