<?php
function searchArrayWithMultipleOption(array $array = null, array $search = null, bool $isMultiple = true){
if (empty($array) || empty($search)) { return []; }
$matchedItems = [];
foreach($array as $key => $item) {
$isMatched = true;
foreach($search as $searchKey => $searchValue) {
if(!(isset($item[$searchKey]) && ((is_array($searchValue) ? in_array($item[$searchKey], $searchValue) : $item[$searchKey] == $searchValue)))) {
$isMatched = false;
break;
}
}
if($isMatched) {
if(!$isMultiple){ return $item; }
$matchedItems[] = $item;
}
}
return $isMultiple ? $matchedItems : [];
}
function getAllSons(array $data, mixed $id, bool $retArr = false) : array {
if (empty($data) || !isset($data[0]['pid'])) {
throw new InvalidArgumentException('Invalid data or missing pid field');
}
$result = [];
$stack = [$id];
$visited = [];
while (!empty($stack)) {
$currentId = array_pop($stack);
if (isset($visited[$currentId])) {
continue;
}
$visited[$currentId] = true;
foreach ($data as $index => $node) {
if ($node['id'] === $currentId) {
if ($retArr) {
$result[] = $node;
} else {
$result[] = $node['id'];
}
foreach ($data as $childNode) {
if ($childNode['pid'] === $currentId) {
$stack[] = $childNode['id'];
}
}
break;
}
}
}
return $result;
}
$navigationArray = [
[
'id' => 1,
'title' => '首页',
'link' => '/home',
'status' => 0,
'pid' => 0
],
[
'id' => 2,
'title' => '关于我们',
'link' => '/about',
'status' => 1,
'pid' => 1
],
[
'id' => 3,
'title' => '产品介绍',
'link' => '/products',
'status' => 1,
'pid' => 1
],
[
'id' => 4,
'title' => '服务支持',
'link' => '/support',
'status' => 1,
'pid' => 2
],
[
'id' => 5,
'title' => '最新资讯',
'link' => '/news',
'status' => 0,
'pid' => 1
],
[
'id' => 6,
'title' => '合作伙伴',
'link' => '/partners',
'status' => 0,
'pid' => 2
],
[
'id' => 7,
'title' => '联系我们',
'link' => '/contact',
'status' => 0,
'pid' => 3
],
[
'id' => 8,
'title' => '人才招聘',
'link' => '/careers',
'status' => 1,
'pid' => 3
],
[
'id' => 9,
'title' => '客户反馈',
'link' => '/feedback',
'status' => 1,
'pid' => 5
],
[
'id' => 10,
'title' => '帮助中心',
'link' => '/help',
'status' => 1,
'pid' => 3
],
];
$res = searchArrayWithMultipleOption($navigationArray, ['pid'=>3, 'status'=> 1], false);
$res = getAllSons($navigationArray, 1, false);
print_r($res);