dongzichan2886 2018-09-25 23:26
浏览 132
已采纳

按条件在多维数组上的PHP array_filter()

I've the below array of users:

$users = [
  [name => 'Alice', age => 22],
  [name => 'Bob', age => 23],
  [name => 'Charlie', age => 19]
];

I'd like to create an array of users that are at least 20 years old. I tried:

$allowed_users = array_filter($users, function($user) {
  return $user->age >= 20;
});
var_dump($allowed_users);

Which returns an empty array. I suppose I'm doing something wrong with the callback function.

  • 写回答

4条回答 默认 最新

  • douyingbei1458 2018-09-25 23:31
    关注

    You are using object notation with an array. It's a simple fix:

    $users = [
      ['name' => 'Alice', 'age' => 22],
      ['name' => 'Bob', 'age' => 23],
      ['name' => 'Charlie', 'age' => 19]
    ];
    
    $allowed_users = array_filter($users, function($user) {
      return $user['age'] >= 20;
    });
    var_dump($allowed_users);
    

    And although it's not an error in itself, use quotes in your keys, otherwise the interpreter will throw a notice.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan