How to use array values as keys without loops?

前端 未结 6 1652
暗喜
暗喜 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)

    0 讨论(0)
  • 2020-12-09 16:43

    This is the fastest and simplest code here so far ...

    $result = [];
    foreach ($input as $subarray) {
        $result[$subarray["id"]] = $subarray["name"];
    }
    
    0 讨论(0)
  • 2020-12-09 16:50

    UPD: Warning the slowest solution! See benchmarks below.

    Try this code:

    $a = array(array('id'   => 1234,
                     'name' => 'blablabla'),
               array('id'   => 1235,
                     'name' => 'ababkjkj'),
               array('id'   => 1236, 
                     'name' => 'xyzxyzxyz'));
    
    var_export(array_reduce($a, function($res, $item) {
        $res[$item['id']] = $item['name'];
        return $res;
    }));
    

    Works fine even in PHP 5.3. And uses only one function array_reduce.

    UPD: Here are some benchmarks (PHP 5.6 over Debian 7 on a medium quality server):

    $a = [];
    for ($i = 0; $i < 150000; $i++) {
        $a[$i] = ['id' => $i,
                   'name' => str_shuffle('abcde') . str_shuffle('01234')];
    }
    
    $start = microtime(true);
    
    if (false) {
        // 7.7489550113678 secs for 15 000 itmes
        $r = array_reduce($a, function($res, $item) {
                 $res[$item['id']] = $item['name'];
                 return $res;
             });
    }
    
    if (false) {
        // 0.096649885177612 secs for 150 000 items
        $r = array_combine(array_column($a, 'id'),
                           array_column($a, 'name'));
    }
    
    if (true) {
        // 0.066264867782593 secs for 150 000 items
        $r = [];
        foreach ($a as $subarray) {
            $r[$subarray['id']] = $subarray['name'];
        }
    }
    
    if (false) {
        // 0.32427287101746 secs for 150 000 items
        $r = [];
        array_walk($a, function($v) use (&$r) {
            $r[$v['id']] = $v['name'];
        });
    }
    
    echo (microtime(true) - $start)  . ' secs' . PHP_EOL;
    

    So, as a conclusion: plain iteration with simple for loop is a winner (as mentioned in this answer). On a second place there is array_combine allowed only for new versions of PHP. And the worst case is using my own solution with closure and array_reduce.

    0 讨论(0)
  • 2020-12-09 16:51

    Try this function:

    array_combine(array_column($array,'id'), array_column($array,'name'));
    
    0 讨论(0)
  • 2020-12-09 17:00

    Make use of array_map function, (PHP 4 >= 4.0.6, PHP 5)

    [akshay@localhost tmp]$ cat test.php
    <?php
    
    $array = array(
                    array('id'   => 1234,'name' => 'blablabla'),
                    array('id'   => 1235,'name' => 'ababkjkj'),
                    array('id'   => 1236,'name' => 'xyzxyzxyz')
                  );
    
    $output = array();
    array_map(function($_) use (&$output){ $output[$_['id']] = $_['name']; },$array);
    
    // Input
    print_r($array);
    
    // Output
    print_r($output);
    
    ?>
    

    Output

    [akshay@localhost tmp]$ php test.php
    Array
    (
        [0] => Array
            (
                [id] => 1234
                [name] => blablabla
            )
    
        [1] => Array
            (
                [id] => 1235
                [name] => ababkjkj
            )
    
        [2] => Array
            (
                [id] => 1236
                [name] => xyzxyzxyz
            )
    
    )
    Array
    (
        [1234] => blablabla
        [1235] => ababkjkj
        [1236] => xyzxyzxyz
    )
    
    0 讨论(0)
  • 2020-12-09 17:09

    If you have php >= 5.5:

    $res = array_combine(array_column($source, 'id'), array_column($source, 'name'));
    

    If not - make a loop.

    0 讨论(0)
提交回复
热议问题