duanchazhou6779 2011-11-03 12:01
浏览 52
已采纳

如何在没有循环的情况下在多维数组中获取特定“键”的数组

Let's assume I have the following multidimensional array (retrieved from MySQL or a service):

array(
    array(
        [id] => xxx,
        [name] => blah
    ),
    array(
        [id] => yyy,
        [name] => blahblah
    ),
    array(
        [id] => zzz,
        [name] => blahblahblah
    ),
)

Can we get an array of ids in one "built-in" php function call? or one line of code?
I am aware of the traditional looping and getting the value but I don't need this:

foreach($users as $user) {
    $ids[] = $user['id'];
}
print_r($ids);

Maybe some array_map() and call_user_func_array() can do the magic.

  • 写回答

4条回答 默认 最新

  • douliao1911 2011-11-03 12:06
    关注

    Since php 5.5, you can use array_column:

    $ids = array_column($users, 'id');
    

    Since php 5.3, you can use array_map with an anonymous function, like this:

    $ids = array_map(function ($ar) {return $ar['id'];}, $users);
    

    Before(Technically php 4.0.6+), you must create an anonymous function with create_function instead:

    $ids = array_map(create_function('$ar', 'return $ar["id"];'), $users);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号