2016-10-17 09:52
浏览 159

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:

Any help will be greatly appreciated :)

图片转代码服务由CSDN问答提供 功能建议


这是一个Symfony 3应用程序,但问题是纯PHP,它涉及某种递归。

我有一个多维数组 它代表我的嵌套形式和需要映射到表单字段的错误(我知道该怎么做)。


我需要递归地遍历 fields 的子代,当我到达终点时 一个节点,它包含 message 键(只是一种确认我已经达到错误的方法)然后将其应用于表单 // apply to form here 然后删除该索引 / node,以便递归不会再次沿着那条路走下去?

任何人都可以帮助func 会做到这一点。 就像我说的那样,知道Symfony只是帮助重复一个多维数组的函数并在再次调用之前移除该节点并不重要。

我的课程就在那里 >但如果我可以按照数组键,我可以减少至少50%


  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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...
        // Delete the item from your array
    解决 无用
    打赏 举报

相关推荐 更多相似问题