douchendan0040 2016-10-17 09:52
浏览 160
已采纳

PHP - 多维数组递归

I have an a problem I know how to tackle it but not 100% clear on what the implementation would look like.

This is a Symfony 3 app but the problem is a pure PHP one which involves some kind of recursion.

I have a multi-dimensional array which represents my nested form and and an errors that need to be mapped to a form field (that bit I know how to do).

Here is my array:

enter image description here

I need to loop over the children of fields recursively and when I reach the end of a node and it contains message key (just a way to confirm I have reached the error) then apply that to the form // apply to form here then remove that index/node so that the recursion doesn't go down that route again?

Can anyone help with the function that will do this. Like I said it is not important to know Symfony just help with the function that will recurs a mutli-dimensional array and remove that node before calling itself again.

My class at it stands but I can cut atleast 50% of this if I can just follow the array keys:

http://laravel.io/bin/ok5n9

Any help will be greatly appreciated :)

  • 写回答

2条回答 默认 最新

  • doubeng3412 2016-10-17 10:01
    关注

    When looping through your array, use a for loop so you can easily manipulate indexes:

    for($i = 0; $i < count($fields); $i++) {
        // You can use $fields[$i] here for the current item
    }
    

    Using isset(), you can check if the message key exists in the fields array. If that is true, use the continue keyword to skip over the current item and continue with the next one.

    It will look something like this, you can change it according to your needs:

    for($i = 0; $i < count($fields); $i++) {
        if (isset($fields[$i]['message')) {
            // error exists...
            continue;
        }
    
        // Delete the item from your array
        unset($fields[$i]);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀