Search code examples
phparrayslaravel-5ormarray-column

Get two columns of data as an array of keys and values using Laravel


What is the Laravel's way to retrieve an associative array in which, the keys are the first column of a query and the values are the second column.

User::select('id','type')->unknown();

should return:

[
2=>'s',  
30=>'t',
32=>'x',
]

Solution

  • I don't think that method exists, but what you could do is use array_column on the returned associative array to get what you want:

    $array = User::select( 'type', 'id' )->all();//get array of assoc arrays
    $result = array_column($array, 'type', 'id');//column
    

    this will return an array using the id key in each sub array of $array (ie each result/assoc array) as key, and the type value as value. So if $array looks like this:

    $array = [
        [
            'id'   => 1,
            'type' => 'a',
        ],
        [
            'id'   => 2,
            'type' => 'b',
        ],
    ];
    

    The result of the array_column call will look like this:

    $result = [
        1 => 'a',
        2 => 'b',
    ];
    

    Note array_column requires PHP 5.5 or higher, if you're running 5.4, and you can't upgrade, write your own function, it's easy enough:

    function myArrayCol(array $in, $valKey, $idxKey = null)
    {
        $result = [];
        foreach ($in as $sub) {
            if (!is_array($sub)) {
                throw new RuntimeException('myArrayCol requires a multi-dimensional array to be passed');
            }
            $value = isset($sub[$valKey]) ? $sub[$valKey] : null;
            if ($idxKey === null || !isset($sub[$idxKey])) P
                $result[] = $value;
            } else {
                $result[$sub[$idxKey]] = $value;
            }
        }
        return $result;
    }
    

    Note this implementation is completely untested, but you get the basic idea...


    Update

    Aparently, laravel does have a method that does what the OP wants, as @Mat suggested, and the docs show:

    $result = User::lists('type', 'id')->all();
    

    That returns the result the OP is after in a one-liner.