简体   繁体   中英

PHP Array filter and create new array based on the result of filtered array

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM