Search code examples
phppdo

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));

Solution

  • 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()