user1744974
user1744974

Reputation: 25

Getting array in different format from data fetched using SQL

After executing a prepared SQL statement in PHP, I've doing a fetchAll(). This results in the following array:

Array
(

    [0] => Array
    (
        [ID] => 2
        [0] => 2
        [latitude] => 38.44560000
        [1] => 38.44560000
        [longitude] => -99.99999999
        [2] => -99.99999999
    )
    [1] => Array
    (
        [ID] => 4
        [0] => 4
        [latitude] => 38.44560000
        [1] => 38.44560000
        [longitude] => -99.99999999
        [2] => -99.99999999
    )
)

I would like my array to look like this:

Array
(

    [0] => array('2','otheritem1details....','38.44560000','-99.99999999'),
    [1] => array('4','otheritem1details....','38.44560000','-99.99999999')
)

Do I have to take the data from the source array and manually compile it into a new array in the correct format? Or is there a way to fetch the data initially in the correct format?

Many thanks.

Upvotes: 0

Views: 57

Answers (1)

user3942918
user3942918

Reputation: 26375

fetchAll() takes a fetch style as an optional first parameter. This defaults to PDO::FETCH_BOTH.

From the manual:

PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set

What you want is PDO::FETCH_NUM:

PDO::FETCH_NUM: returns an array indexed by column number as returned in your result set, starting at column 0

So your call to fetchAll would look something like $sth->fetchAll(PDO::FETCH_NUM)

Upvotes: 3

Related Questions