我怎样才能遍历这个数组 - PHP

时间:2012-10-24 07:04:06

标签: php loops foreach

这是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
                 }
            }   


        }

按要求打印__()

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
        )

)

3 个答案:

答案 0 :(得分: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';
        }
    }   
}

这是working example

答案 1 :(得分:0)

试试这个?

if(!is_null($options)){
    foreach($options as $option){
        if(!array_key_exists('parent_'.$option.'_children',$options)){
            throw new Exception("Something went wrong!");
        }
    }   
}

答案 2 :(得分: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
相关问题