2012-10-24 83 views
0

这是var_dump($options)我怎样才能通过这个数组循环 - PHP

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 
     ) 

) 
+1

当你循环阅读时你想做什么? –

+0

如果position null输出错误 – Techie

+0

您现有的代码应该没问题。 –

回答

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 
+0

不向屏幕输出任何内容。问题用print_r更新 – Techie

+0

现在,它不会输出任何东西,因为阵列中存在两个数组键parent_'。$ option .'_ children – janenz00

+0

@Dasun - 我添加了一个带有错误条件的测试数组 – janenz00

1

的print_r()使用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

+0

什么都不输出到屏幕上。问题用print_r更新 – Techie

+0

你想要它做什么?我可以抛出一个异常,或回显一些文字......我会更新。但是请注意,只有在密钥不存在的情况下它才会显示。 – VDP

+0

我已经在echo'parent _'。$ option。'_ children';这个。不起作用 – Techie

0

试试这个?

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