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',
]
1

2 Answers 2

2

It should be:

User::lists( 'type', 'id' )->all();
Sign up to request clarification or add additional context in comments.

3 Comments

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
@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: 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
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.

1 Comment

Thanks. I guess the first two code blocks should be swap .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.