Sławomir Kudła
Sławomir Kudła

Reputation: 291

PDO return objects ids in keys

hey i have array with returned keys

$temp = $sth->fetchAll(PDO::FETCH_ASSOC);

my result looks like this:

[0] => [
    'id' = 11,
    'title' => 't1'
]

[1] => [
    'id' = 12,
    'title' => 't2'
]

if i want to return ids as key i call something like this:

$temp = array_map(function($v){return $v[0];}, $sth->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC));

and my resoult looks like this:

[11] => [
    'title' => 't1'
]

[12] => [
    'title' => 't2'
]

how to return array of objects by ID? when i do this i dont have methods in object...

$temp = array_map(function($v){return $v[0];}, $sth->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_CLASS));

Upvotes: 3

Views: 2705

Answers (3)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72289

I will do a bit easier code like below:-

$fianl_array = array_combine(array_column($temp,'id'),$temp);

Final Output:-

Array
(
    [11] => Array
        (
            [id] => 11
            [title] => t1
        )

    [12] => Array
        (
            [id] => 12
            [title] => t2
        )

)

Reference:-

array_column()

array_combine()

Upvotes: 5

Nigel Ren
Nigel Ren

Reputation: 57121

Just had to add this as an answer as I believe it's the shortest way of doing this, using array_column() with a third parameter which is the key you want the data indexed by. If you use null as the second parameter, it will index all the data by 'id', you could instead use 'title' and this will only index the title columns by ID...

$output = array_column($temp,null,'id');

Which gives...

Array
(
    [11] => Array
        (
            [id] => 11
            [title] => t1
        )

    [12] => Array
        (
            [id] => 12
            [title] => t2
        )

)

Upvotes: 1

Karlo Kokkak
Karlo Kokkak

Reputation: 3714

Using foreach:

foreach($input as $k=>$v){
    $output[$v['id']] = array('title'=>$v['title']);
}
print_r($output);

Upvotes: 1

Related Questions