Is it possible to assign keys to array elements in PHP from a value column with less code?

前端 未结 3 1121
日久生厌
日久生厌 2021-01-20 00:16

Let\'s assume I have an array of elements, which are arrays themselves, like so:

$array = [
    [\'foo\' => \'ABC\', \'bar\' => \'DEF\'],
    [\'foo\'          


        
相关标签:
3条回答
  • 2021-01-20 00:28

    Notice array-column can get index as well (third argument):

    mixed $index_key = NULL

    So just use as:

    array_column($array, null, 'foo');
    
    0 讨论(0)
  • 2021-01-20 00:38

    You can also do it with array_reduce

    $new_array = array_reduce($array, function($carry, $item) {
        $carry[$item['foo']] = $item;
        return $carry;
    }, []);
    
    0 讨论(0)
  • 2021-01-20 00:45

    Here is one liner for your case,

    $temp = array_combine(array_column($array, 'foo'), $array);
    

    Working demo.

    array_combine — Creates an array by using one array for keys and another for its values
    array_column — Return the values from a single column in the input array

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