Skip to content
Advertisement

How to get Table field names at top of result array

Here is my Sample table:

enter image description here

Here is My Query:

SELECT * FROM table

Result for above query is:

Array
    (
        [0] => Array
            (
                [id] => 1
                [name] => a
                [country] => x
            )
        [1] => Array
            (
                [id] => 2
                [name] => b
                [country] => y
            )
    )

I need to get the field names in the first element of the array.

Expected result array is:

Array
(
    [0] => Array
        (
            [id] => id
            [name] => name
            [country] => country
        )
    [1] => Array
        (
            [id] => 1
            [name] => a
            [country] => x
        )
    [2] => Array
        (
            [id] => 2
            [name] => b
            [country] => y
        )
)

How can I modify the Query to get this result?

Thanks in advance…

Advertisement

Answer

Display issues should generally be dealt with in application code, not SQL queries. If you have your values in an array (called $results, say), you can use this code to add the desired entry:

array_unshift($results, array_combine(array_keys($results[0]), array_keys($results[0])));
print_r($results);

Output:

Array
(
    [0] => Array
        (
            [id] => id
            [name] => name
            [country] => country
        )
    [1] => Array
        (
            [id] => 1
            [name] => a
            [country] => x
        )
    [2] => Array
        (
            [id] => 2
            [name] => b
            [country] => y
        )
)

Demo on 3v4l.org

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement