duanjian4698 2018-06-03 05:55
浏览 15
已采纳

返回嵌套数组键名而不是索引

I'm trying to return the name and value by looping through an array and for that I'm using the array_walk_recursive function. All works fine, except that it's returning the nested array indexes instead of the name. In the example below I want the indexes to be 'name3' but as the main array is dynamic, the loop can't be specific for that nested array.

Array

   Array
(
    [name1] => value
    [name2] => value
    [name3] => Array
        (
            [0] => value1
            [1] => value2
        )

)

Function

function test($value, $name) {
   echo "<input type='hidden' name='$name' value='$value'>";
}
array_walk_recursive($array, 'test');

Output

<input type='hidden' name='name1' value='value'>
<input type='hidden' name='name2' value='value'>
<input type='hidden' name='0' value='value1'>
<input type='hidden' name='1' value='value2'>
  • 写回答

2条回答 默认 最新

  • dongmei5168 2018-06-05 00:44
    关注

    It was simpler than i thought, a nested foreach is needed for that.

    foreach ($array as $name => $value) {
      if (is_array($value)) {
        foreach ($value as $name2 => $value2) { 
          echo '<input type="hidden" name="'.$name."[]".'" 
             value="'.$value2.'">';
        } 
      } else {
          echo '<input type="hidden" name="'.$name.'" value="'.$value.'">';
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 wordpress项目注册报失败刷新后其实是成功状态,请求排查原因
  • ¥20 linxu服务器僵尸进程不释放,代码如何修改?
  • ¥15 pycharm激活不成功
  • ¥40 如果update 一个列名为参数的value
  • ¥15 基于51单片机的水位检测系统设计中LCD1602一直不显示
  • ¥15 OCS2安装出现问题,请大家给点意见
  • ¥15 ros小车启动launch文件报错
  • ¥15 vs2015到期想登陆但是登陆不上
  • ¥15 IPQ5018制作烧录固件,boot运行失败(操作系统-linux)(相关搜索:操作系统)(相关搜索:操作系统)
  • ¥20 icefall在librispeech基础上加入个人数据集