2

So I have a variable $offices['results'] when var dumped will output like this:

array() {
  [0]=>
  object(stdClass)#16067 (24) {
    ["id"]=>
    string(1) "4"
    ["blog_id"]=>
    string(2) "10"
    ["office_name"]=>
    string(0) "Japan"
  }
  [1]=>
  object(stdClass)#16064 (24) {
    ["id"]=>
    string(1) "5"
    ["blog_id"]=>
    string(2) "11"
    ["office_name"]=>
    string(0) "USA"
  }
[2]=>
  object(stdClass)#16064 (24) {
    ["id"]=>
    string(1) "5"
    ["blog_id"]=>
    string(2) "12"
    ["office_name"]=>
    string(0) "USA"

  }
}

I only want to create a new array variable where the blog_id is 10 and 12, which will return:

array() {
  [0]=>
  object(stdClass)#16067 (24) {
    ["id"]=>
    string(1) "4"
    ["blog_id"]=>
    string(2) "10"
    ["office_name"]=>
    string(0) "Japan"
  }   
[1]=>
  object(stdClass)#16064 (24) {
    ["id"]=>
    string(1) "5"
    ["blog_id"]=>
    string(2) "12"
    ["office_name"]=>
    string(0) "USA"

  }
}

I tried array_filter but I cant make it work.

$array = $offices['results'];

$like = '11','12';

$result = array_filter($array, function ($item) use ($like) {
    if (stripos($item['blog_id'], $like) !== false) {
        return true;
    }
    return false;
});
var_dump($result);

I hope you can help me. Thanks

5
  • 1
    How did you try array_filter? Commented Mar 31, 2020 at 5:37
  • @shingo, sorry I forgot to input, I just edited my question Commented Mar 31, 2020 at 5:40
  • Really? It would just be return $value->blog_id == 10 || $value->blog_id == 12 Commented Mar 31, 2020 at 5:40
  • What data type is this? $like = '11','12'; Commented Mar 31, 2020 at 5:43
  • @Andreas yes like that Commented Mar 31, 2020 at 5:46

2 Answers 2

1

You could iterate through this array and check if the blog_id exists or not

but first, let's assign an array with your blog_id you want

$blogs = [10, 12];

after that, you can start iterate through your data

$result = [];
foreach($data as $blog){
  if(in_array($blog->blog_id, $blogs)){
     $result[] = $blog;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

the $data is the $offices['results'] , is that right?
1

Not tested but how about this way with array_filter()?

$filterBy = [10,12];
$array = $offices['results'];
$newArray = array_filter($array, function ($var) use ($filterBy) {
    return in_array($var->blog_id,$filterBy);
});

2 Comments

Im sorry Im confused, but how did you called the $offices['results'] in your code? because what I know is you will need to call the first array $offices['results'];? like in my code above I called it first $array = $offices['results']
@ICGDEVS exactly, Yes I just added the demo code so you can fix easily :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.