doulaobi7988 2013-09-12 15:58
浏览 47
已采纳

解析嵌套数组(PHP)

I am trying to find an efficient way to do the following :

1) Parse an array. 2) If the element is a single value, store it/echo it. 3) If the element is an array, Parse it and store/echo all of its elements.

An example would be :

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

This would be echo'd as :

15 25 Dog 11 Cat Cookie15 22

Note : The maximum number of Nested layers of Arrays = 2 (The max is an Array within an Array, not deeper than that).

The code I have made so far is :

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  ";
      }
}

Edit: The following is my dump for the array. The nested elements show blank for some odd reason!

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)

The relevant code is :

foreach($_POST as $input) {
 var_dump($input);
}
  • 写回答

3条回答 默认 最新

  • douyao7390 2013-09-12 16:05
    关注

    This should do the trick

    PS.: I edit the call to the function, i was calling it inside a foreach, now i'm just sending $_POST wich is correct.

    Second edit: I'm not saving the function inside a variable anymore, instead i'm declaring it.

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计