PDO fetch array

2

I would like to know if there is any way to rename the keys of an associative array that is given by PDOStatement :: fetch. The sentence that I prepare and execute in SQL does not come to the case in itself (although if they require it, I can add it). The fact is that I ask my database for several records through INNERs and in 3 tables the column "id" is repeated. When I want to access through the array that PDO returns, problems arise due to the names of the keys, which makes development very difficult for me. I tried to specify the fetch mode to 'NUM' without success (by default, FETCH () sets the mode to FETCH_BOTH). Will there be any way to rename the array keys?

Note: I have thought about changing the names of the columns, since at this moment they are few, but I would not believe that it was a viable solution (or very intelligent).

I have also thought about using the function array_map () and going unlinking with unset, but being a non-native in php, I have not obtained good results.

Thank you in advance.

    
asked by Faju 04.01.2018 в 21:30
source

1 answer

3

The simplest thing would be:

For the query

Use aliases for those columns that you want to be called different, giving them the names you want, for example:

SELECT t1.id, 
       t2.id as id_tabla2, 
       t3.id as id_tabla3...

The use of aliases does not mean that you change the names of the columns in your tables directly, but for that particular query you assign a nickname to certain columns. Precisely the aliases are used to differentiate columns that are called equal, when several tables intervene in the query. The real name remains intact, but for that result the column acquires a different name.

In the results

Use PDO::FETCH_ASSOC , which will return an array indexed by the names of the columns in the set of results.

You will then have an array whose key names will be:

id 
id_tabla2
id_tabla3 ...

Using other procedures, other than having an impact on the performance of the application, could produce unexpected results.

On the other hand, a SELECT with aliases, would allow you to give another name to the column without having to modify the table itself, which could cause errors, especially if you have queries scattered throughout the application.

    
answered by 04.01.2018 / 21:50
source