How to use array values as keys without loops?

前端 未结 6 1624
暗喜
暗喜 2020-12-09 16:12

Looping is time consuming, we all know that. That\'s exactly something I\'m trying to avoid, even though it\'s on a small scale. Every bit helps. Well, if it\'s unset of co

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-09 16:43

    Simply use array_combine along with the array_column as

    array_combine(array_column($array,'id'), array_column($array,'name'));
    

    Or you can simply use array_walk if you have PHP < 5.5 as

    $result = array();
    array_walk($array, function($v)use(&$result) {
        $result[$v['id']] = $v['name']; 
    });
    

    Edited:

    For future user who has PHP > 5.5 can simply use array_column as

    array_column($array,'name','id');
    

    Fiddle(array_walk)

提交回复
热议问题