Reputation: 909
Hello!!
i think its very simple question for those who familier with std objects and arrays in PHP.
Here is my STD Object array:
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 ) )
now, i have different array with numbers for example:
$arr=array(17,10);
and i need to check if one of this numbers is equal the [category_id] value (inside the std object), if it is equal, check the next [category_id], and if it's not, remove all values of this object . (of course, Other method is to build a new STD Object only with the numbers in the array)
So the result should be:
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 ) )
Only the array's with categiry_id =17 and 10 are inside this stdObject..
Thank you very much for your help!!
Eran.
Upvotes: 1
Views: 2194
Reputation: 5683
Try this
$arr=array(17,10);
foreach ($array as $key => $obj) {
if (!in_array($obj->category_id, $arr)) {
unset($array[$key]);
}
}
// edited, missing closing bracket
Upvotes: 3
Reputation: 95141
You can use array_filter
to filter what you want or what you don't want
$filterCategory = array(17,10);
$array = array_filter($yourArray,function($var) use($filterCategory) { return in_array($var->category_id, $filterCategory); } );
Upvotes: 1