1

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

ICG DEVS
  • 195
  • 3
  • 15

2 Answers2

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);
});
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • 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']` – ICG DEVS Mar 31 '20 at 05:46
  • 1
    @ICGDEVS exactly, Yes I just added the demo code so you can fix easily :) – A l w a y s S u n n y Mar 31 '20 at 06:05
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;
  }
}
Joseph
  • 5,644
  • 3
  • 18
  • 44