我如何创建在多维嵌套数组中搜索的搜索功能?
给出以下数组:
Array
(
[0] => Array
(
[id] => 1
[parent_name] => ACTIVITIES
[children] => Array
(
)
)
[1] => Array
(
[id] => 2
[parent_name] => ANIMALS/PETS
[children] => Array
(
)
)
[2] => Array
(
[id] => 3
[parent_name] => ART
[children] => Array
(
[0] => Array
(
[post_id] => 100
[child_name] => Bookeeping
[painting] => Array
(
[0] => flower
[1] => beach
[2] => sunrise
)
)
[1] => Array
(
[post_id] => 101
[child_name] => Addiction
[painting] => Array
(
[0] => sunrise
[1] => beach
)
)
)
)
[3] => Array
(
[id] => 4
[parent_name] => Music
[children] => Array
(
[0] => Array
(
[post_id] => 102
[child_name] => POP
[painting] => Array
(
[0] => suntown
[1] => beachfull
[2] => sunrise
)
)
[1] => Array
(
[post_id] => 103
[child_name] => Rock
[painting] => Array
(
[0] => sunrisenew
[1] => beachnew
)
)
)
)
)
我如何使用在“绘画”中搜索的键来过滤此数组?
例如,搜索键为“ sun”
结果应如下所示:
Array
(
[2] => Array
(
[id] => 3
[parent_name] => ART
[children] => Array
(
[0] => Array
(
[post_id] => 100
[child_name] => Bookeeping
[painting] => Array
(
[2] => sunrise
)
)
[1] => Array
(
[post_id] => 101
[child_name] => Addiction
[painting] => Array
(
[0] => sunrise
)
)
)
)
[3] => Array
(
[id] => 4
[parent_name] => Music
[children] => Array
(
[0] => Array
(
[post_id] => 102
[child_name] => POP
[painting] => Array
(
[0] => suntown
)
)
[1] => Array
(
[post_id] => 103
[child_name] => Rock
[painting] => Array
(
[0] => sunrisenew
)
)
)
)
)
答案 0 :(得分:0)
$needle = "sun";
$filteredArr = array_filter(
$arr,
function($v) use ($needle) {
foreach($v['children'] as $child) {
// "Version 1" of filtering, no "parts of strings" searches
if (in_array($needle, $child['painting'])) {
return true;
}
// "Version 2" of filtering, keyword may be part of a painting string
foreach($child['painting'] as $painting) {
if (strpos($painting, $needle) !== false) {
return true;
}
}
}
return false;
}
);
如果对array_filter()使用回调,则可以进行相当高级的过滤。
修改 新版本的答案可以删除绘画阵列中与模式不匹配的条目。
这是通过执行嵌套的foreach循环来完成的,一直循环到所需的最里面的数组,在这种情况下为 painting 。 过滤 painting 数组,以便删除其中的所有不匹配元素。 完成此操作后,在下一个向外的级别检查 painting 数组,如果为空,则清除类型为“向外传播”。这样,只有带有匹配绘画条目的条目才应保留,并且应该具有可扩展性。
这些引用不是严格必需的,可以将数组键变量添加到foreach循环中。但是我不喜欢造成这种情况的所有索引。
$needle = 'sun';
foreach($arr as $entryKey => &$entry) {
foreach($entry['children'] as $childKey => &$child) {
foreach($child['painting'] as $paintingKey => $painting) {
if (strpos($painting, $needle) === false) {
unset($child['painting'][$paintingKey]);
}
}
if (empty($child['painting'])) {
unset($entry['children'][$childKey]);
}
}
if (empty($entry['children'])) {
unset($arr[$entryKey]);
}
}
unset($entry, $child); // Take no risks with references