PDO fetchAll() primary key as array group key

后端 未结 6 894
南笙
南笙 2020-12-10 04:26

I want to store the contents of a specific database into an array, grouped by their primary keys. (Instead of the useless way PDO fetchAll() organises them).

My curr

6条回答
  •  Happy的楠姐
    2020-12-10 04:47

    I'm still suggesting you to loop using fetch() method. Otherwise, you can use array_reduce() to iterate over the array. A sample on codepad is here.

    The code(in human readable form) will be:

    $myFinalArray = array_reduce($myInputArray, function($returnArray, $temp) { 
        $temp2 = $temp['id']; 
        unset($temp['id']); 
        $returnArray[$temp2] = $temp; 
        return $returnArray;
      }
    );
    

提交回复
热议问题