When I'm using pg_fetch_assoc then my output like below
[{"0":"T","id":"I","1":"T-ABC"},
{"0":"T","id":"I","1":"T-XYZ"},
{"0":"T","id":"I","1":"T-QWR"}]
But right now I'm using Laravel framework and in my controller am using below code
$type=$request->type;
$query= typeModel::get()->where('id',$type);
return response()->json($query);
The above code is give me below format
{"11":{"id":"I","type":"T-ABC"},
"12":{"id":"I","type":"T-XYZ"},
"13":{"id":"I","type":"T-OWR"}}
But I need format like pg_fetch_assoc How can i achieve this in laravel
Using eloquent collection method map()
to map every stdClass;
Because pg_fetch_assoc
return the column name, column value, index key and index value;
So we can use array_merge
to merge two array.
The one is $array1
including column name, column value;
The other one is $array2
only have all the column value;
Convert array to stdClass, it will automatically add index key on that $array2
, and this index key is start from 0
:
$query = typeModel::where('id',$type)->get()->map(function($item) {
$array1 = $item->toarray();
$array2 = array_values($array1);
return (object) array_merge($array1, $array2);
})->toArray();