1

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.

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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); } );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.