1

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',
]
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Handsome Nerd
  • 17,114
  • 22
  • 95
  • 173
  • Related: [Generate an associative array from an array of rows using one column as keys and another column as values](https://stackoverflow.com/q/3690515/2943403) – mickmackusa Jan 16 '23 at 04:08

2 Answers2

2

It should be:

User::lists( 'type', 'id' )->all();
Mat
  • 2,156
  • 2
  • 16
  • 29
  • Read the question, OP wants the keys of the array to be the `id`'s, and the values to be the `type` values in the array. `->all` will return an array of associative arrays – Elias Van Ootegem Nov 14 '15 at 14:41
  • 1
    @EliasVanOotegem No it won't. `lists` does exactly what the OP wants.... your `array_column` stuff is unnecessary. This answer needs more explanation though. – andrewtweber Nov 15 '15 at 02:01
  • @andrewtweber: Right you are, didn't notice Mat changed the method that was called. I've updated my answer to include the `lists` method + added a link to the docs. +1 to this answer, though a bit more explanation wouldn't go amiss – Elias Van Ootegem Nov 15 '15 at 12:58
1

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.

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149