你好!
对于那些熟悉PHP中的std对象和数组的人来说,我认为这是一个非常简单的问题。
这是我的STD对象数组:
Array ( [0] => stdClass Object ( [name] => name1 [description] => [category_id] => 17 [category_publish] => 1 [ordering] => 1 [category_parent_id] => 10 ) [1] => stdClass Object ( [name] => name2 [description] => [category_id] => 8 [category_publish] => 1 [ordering] => 1 [category_parent_id] => 0 ) [2] => stdClass Object ( [name] => name3 [description] =>desc [category_id] => 10 [category_publish] => 1 [ordering] => 2 [category_parent_id] => 0 ) [3] => stdClass Object ( [name] => name3 [description] => [category_id] => 16 [category_publish] => 1 [ordering] => 2 [category_parent_id] => 10 ) )
现在,我有不同的数字数组,例如:
$arr=array(17,10);
我需要检查其中一个数字是否等于[category_id]值(在std对象内),如果相等,检查下一个[category_id],如果不相等,则删除该对象的所有值。 (当然,其他方法是仅使用数组中的数字构建新的STD对象)
所以结果应该是:
Array ( [0] => stdClass Object ( [name] => name1 [description] => [category_id] => 17 [category_publish] => 1 [ordering] => 1 [category_parent_id] => 10 ) [2] => stdClass Object ( [name] => name3 [description] =>desc [category_id] => 10 [category_publish] => 1 [ordering] => 2 [category_parent_id] => 0 ) )
只有带有categiry_id = 17和10的数组才在此stdObject中。
非常感谢你的帮助!!
叶兰。
答案 0 :(得分:3)
试试这个
$arr=array(17,10);
foreach ($array as $key => $obj) {
if (!in_array($obj->category_id, $arr)) {
unset($array[$key]);
}
}
// edited, missing closing bracket
答案 1 :(得分:1)
您可以使用array_filter
来过滤您想要的或不想要的内容
$filterCategory = array(17,10);
$array = array_filter($yourArray,function($var) use($filterCategory) { return in_array($var->category_id, $filterCategory); } );