0

我正在尝试找到一种有效的方法来执行以下操作:

1)解析一个数组。2)如果元素是单个值,则存储它/回显它。3)如果元素是一个数组,解析它并存储/回显它的所有元素。

一个例子是:

$array = array(15,25,'Dog',[11,'Cat','Cookie15'],22)

这将被回显为:

15 25 狗 11 猫饼干 15 22

注意:Arrays 的最大嵌套层数 = 2(最大值是 Array 中的 Array,不会比这更深)。

到目前为止我所做的代码是:

foreach($_POST as $key=>$value){  
      if(is_array($value))
      {
      <Not sure how to handle this condition! Need to parse the array and echo individual elements>
      }
      else
      {
       echo "Input name : $key Value : $value  ";
      }
}

编辑:以下是我的数组转储。由于某些奇怪的原因,嵌套元素显示为空白!

string '15' (length=2)

string '25' (length=2)

string 'Dog' (length=3)

array (size=3)
  0 => string '' (length=0)
  1 => string '' (length=0)
  2 => string '' (length=0)

string '22' (length=2)

相关代码是:

foreach($_POST as $input) {
 var_dump($input);
}
4

3 回答 3

3

使用 RecursiveIteratorIterator 和 RecursiveArrayIterator 绝对是最干净的方法:

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));

foreach ($it as $key => $value) {
    var_dump($key, $value);
}


这是我的旧解决方案:

function handle($arr, $deepness=1) {
  if ($deepness == 3) {
    exit('Not allowed');
  }

  foreach ($arr as $key => $value) {
    if (is_array($value)) {
      handle($value, ++$deepness);
    }

    else {
      echo "Input name: $key Value: $value ";
    }
  }
}

handle($_POST);
于 2013-09-12T16:00:30.080 回答
2

这应该可以解决问题

PS.:我编辑了对函数的调用,我在 foreach 中调用它,现在我只是发送 $_POST ,这是正确的。

第二次编辑:我不再将函数保存在变量中,而是声明它。

function recursiveEcho($input){
    if (is_array($input)) {
        foreach ($input as $key => $value) {
            if (is_array($value)) {
                recursiveEcho($value);
            } else {
                echo "Input name: {$key} Value: {$value}";
            }
        }
    } else {
        // This is a string, there is no key to show
        echo "Input value: {$input}";
    }
};

recursiveEcho($_POST);
于 2013-09-12T16:05:56.547 回答
0

This will only handle 1 level. To handle x amount of levels, you either have to use a recursive function, or keep on nesting if statements.

foreach($_POST as $key => $value) {
   if(is_array($value) {
        foreach($value as $key2 => $value2) {
         echo "Key: " .  $key2 . "value: " .$value2;
        }
    } else {
        echo "key" .  $key . "value: ".  $value;
    }

}
于 2013-09-12T16:04:54.207 回答