我正在使用 Wordpress 菜单数组,我需要循环遍历它以根据嵌套对象的值取消设置条目。我目前的做法似乎很笨拙。我确信我可以以某种方式循环遍历数组来完成此任务,但这超出了技能范围(更多的是 JavaScript 人员)。
虽然这是在 WordPress 中,但我认为它更像是一个常见的 PHP 问题,所以我将其发布在这里。
以下是我所拥有的和我正在尝试做的事情的详细说明:
数组示例
Array
(
[1] => WP_Post Object
(
[ID] => 13378;
[title] => Courses;
[current_item_parent] => 1;
)
[2] => WP_Post Object
(
[ID] => 13375;
[title] => Images;
[current_item_parent] => 1;
)
[3] => WP_Post Object
(
[ID] => 13379;
[title] => Tests;
[current_item_parent] => 1;
)
[4] => WP_Post Object
(
[ID] => 13875;
[title] => Somethings;
[current_item_parent] => 1;
)
)
基本上,我想循环遍历下面的数组,如果 Array->title 等于“类(class)”或“测试”,我想从数组中取消设置它。
这就是我到目前为止所拥有的。 $hide 数组没有被使用,但这就是我想要测试的。我那里没有 foreach 循环,因为我无法找到让它工作的方法。
function ad_filter_menu($sorted_menu_objects, $args)
{
$hide = array('Courses', 'Tests'); //doing nothing right now
if ($sorted_menu_objects[1]->title == 'Courses') {
unset($sorted_menu_objects[1]);
};
if ($sorted_menu_objects[3]->title == 'Title') {
unset($sorted_menu_objects[3]);
};
return $sorted_menu_objects;
}
最终结果应该是这样的
Array
(
[2] => WP_Post Object
(
[ID] => 13375
[title] => Images
[current_item_parent] => 1
)
[4] => WP_Post Object
(
[ID] => 13875
[title] => Somethings
[current_item_parent] => 1
)
)
最佳答案
取消实际循环的数组的位总是有点棘手,所以简单的答案是在处理原始数组时创建一个新的
function ad_filter_menu($inArr, $args)
{
$hide = array('Courses', 'Tests');
$newArr = [];
foreach ($inArr as $obj) {
if (! in_array($obj->title, $hide)) {
$newArr[] = $obj;
}
}
return $newArr;
}
The function parameter
$args
does not seem to be used but I left it there in case that was something you were planning to implement later
当然,如果您愿意,也可以从原始数组中删除不需要的项目
function ad_filter_menu2(&$inArr, $args)
{
$hide = array('Courses', 'Tests');
foreach ($inArr as $idx => &$obj) {
if (in_array($obj->title, $hide)) {
unset($inArr[$idx]);
}
}
}
ad_filter_menu2($inArr, 'sssss');
print_r($inArr);
关于php - 根据嵌套对象的值删除数组条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62487049/