Please tell me how to drop an array with Filter with laravel collect.

data are as follows:

$arr = [
    [
        "name" => "Home",
        "rule" => "home",
        "children" => [
            [
                "name" => "index",
                "rule" => "index",
            ],
            [
                "name" => "show",
                "rule" => "show",
            ]
        ],
    ],
    [
        "name" => "File",
        "rule" => "file",
        "children" => [
            [
                "name" => "add",
                "rule" => "add",
            ],
            [
                "name" => "edit",
                "rule" => "edit",
            ]
        ],
    ],
];

$rule = ["home", "index", "file", "edit"];

it is problematic for me to write this way at present, and it is not in line with the expected results.

$collect = collect($arr)
    ->whereInStrict("rule", $rule)
    ->map(function ($value) use ($rule) {
       return collect($value["children"])->whereInStrict("rule", $rule);
    });

dump($collect->toArray());

printed result:

array:2 [
  0 => array:1 [
    0 => array:2 [
      "name" => "index"
      "rule" => "index"
    ]
  ]
  1 => array:1 [
    1 => array:2 [
      "name" => "edit"
      "rule" => "edit"
    ]
  ]
]

the expected result should be as follows:

[
    "name" => "Home",
    "rule" => "home",
    "children" => [
        [
            "name" => "index",
            "rule" => "index",
        ]
    ],
    ],
    [
    "name" => "File",
    "rule" => "file",
    "children" => [
        [
            "name" => "edit",
            "rule" => "edit",
        ]
    ],
],

could you tell me how to write this?

Mar.07,2021

Brother, there is something wrong. The result you screened for the second time should be assigned back to
your code:

$collect = collect($arr)
->whereInStrict('rule', $rule)
->map(function ($value) use ($rule) {
   return collect($value['children'])->whereInStrict('rule', $rule);
});

modify:

$collect = collect($arr)
    ->whereInStrict('rule', $rule)
    ->map(function ($value) use ($rule) {
      $value['children'] = collect($value['children'])->whereInStrict('rule', $rule)
      ->toArray(); //
 return $value;
});

this result is what you want, and there is nothing wrong with the overall thinking.

Menu