0

这是var_dump($options)

array (size=4)
  0 => string '2' (length=1)
  'parent_2_children' => 
    array (size=3)
      0 => string '22' (length=2)
      1 => string '24' (length=2)
      2 => string '23' (length=2)
  1 => string '3' (length=1)
  'parent_3_children' => 
    array (size=3)
      0 => string '26' (length=2)
      1 => string '25' (length=2)
      2 => string '27' (length=2)

我到目前为止所尝试的是

if(!is_null($options))
        {
            foreach($options as $option)
            {
                 if(!array_key_exists('parent_'.$option.'_children',$options))
                 {
                    //if position null output an error
                 }
            }   


        }

按要求打印_r()

Array
(
    [0] => 2
    [parent_2_children] => Array
        (
            [0] => 22
            [1] => 24
            [2] => 23
        )

    [1] => 3
    [parent_3_children] => Array
        (
            [0] => 26
            [1] => 25
            [2] => 27
        )

)
4

3 回答 3

1

使用print_r($options)var_dump更容易阅读..

检查您是否有数字键,然后检查新键是否存在。抛出一个错误。

if(!is_null($options)) {
    foreach($options as $key => $option) {
        if(is_int($key) && !array_key_exists('parent_'.$option.'_children',$options)) {
           echo 'parent_'.$option.'_children does not exist';
        }
    }   
}

这是一个工作示例

于 2012-10-24T07:08:30.017 回答
0

试试这个?

if(!is_null($options)){
    foreach($options as $option){
        if(!array_key_exists('parent_'.$option.'_children',$options)){
            throw new Exception("Something went wrong!");
        }
    }   
}
于 2012-10-24T07:14:28.750 回答
0

你的代码是正确的。对键的性质进行额外检查将减少执行,因为您只需对数字键进行处理。

    if(!is_null($options))
    {
        foreach($options as $key => $option)
        {
            if (is_numeric($key)) {
                 if(!array_key_exists('parent_'.$option.'_children',$options))
                  {
                       print 'parent_'.$option.'_children does not exist';
                   }
             }
        }   


    }

要测试代码,请尝试以下数组:

 $options = array(0 => 2, 'parent_2_children' => array ( 0 => 22, 1 => 24, 2 => 23 ), 1 => 3, 'parent_3_children' => array ( 0 => 26, 1 => 25, 2 => 27 ), 2=>4 ); 

其 print_r 输出将是:

 Array
(
[0] => 2
[parent_2_children] => Array
    (
        [0] => 22
        [1] => 24
        [2] => 23
    )

[1] => 3
[parent_3_children] => Array
    (
        [0] => 26
        [1] => 25
        [2] => 27
    )

[2] => 4

)

并且,它将输出:

  parent_4_children does not exist
于 2012-10-24T07:16:51.323 回答