1

你好!!

我认为对于那些熟悉 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..

非常感谢您的帮助!!

伊兰。

4

2 回答 2

3

试试这个

$arr=array(17,10);
foreach ($array as $key => $obj) {
  if (!in_array($obj->category_id, $arr)) {
    unset($array[$key]);
  }
} 
// edited, missing closing bracket
于 2012-10-13T10:29:29.407 回答
1

你可以array_filter用来过滤你想要的或你不想要的

$filterCategory = array(17,10);
$array = array_filter($yourArray,function($var) use($filterCategory) { return in_array($var->category_id, $filterCategory); } );
于 2012-10-13T10:29:02.257 回答