3

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));
Sławomir Kudła
  • 243
  • 2
  • 4
  • 14

3 Answers3

4

I will do a bit easier code like below:-

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

Output:- https://eval.in/993728

Reference:-

array_column()

array_combine()

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
0

Using foreach:

foreach($input as $k=>$v){
    $output[$v['id']] = array('title'=>$v['title']);
}
print_r($output);
Karlo Kokkak
  • 3,674
  • 4
  • 18
  • 33
0

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
        )

)
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55