H.HISTORY
H.HISTORY

Reputation: 518

Build an array from a MySQL query?

Could someone please let me know how I can create an array from the MySQL query?

The array should look like this:

<?php
$testLocs = array(
    '1' => array( 'info' => '1. New Random info and new position', 'lat' => 45345345, 'lng' => 44.9634 ),
    '2' => array( 'ino'  => '1. New Random info and new position', 'lat' => 686788787, 'lng' => 188.9634),
    '3' => array( 'info' => '1. New Random info and new position', 'lat' => 88888, 'lng' => 144.9634),
    '4' => array( 'info' => '1. New Random info and new position', 'lat' => 666666, 'lng' => 144.964 )
);
echo json_encode($testLocs);
exit();
?>

Where the text for info and numbers for lat and lng are MySQL $rows.

Any help would be appreciated.

Upvotes: 0

Views: 62

Answers (3)

Matt Jameson
Matt Jameson

Reputation: 582

   $testLocs = array();

   $sql = <<<SQL
            SELECT id, info, position, lat, lng
            FROM tbl_info
SQL;

    $q = mysql_query($sql);    

    while ($r = mysql_fetch_assoc($q)) {
        $testLocs[$r['id']] = $r;
    }

    print_r($testLocs);

Obviously replace the query with the correct one.

PS. This is the mysql way, not the mysqli way. It might be worth looking at both.

Upvotes: 1

Jan.J
Jan.J

Reputation: 3080

If I undestand it correctly you need to map mysql array results to some kind of normalized array. Function array_map would be perfect for it:

$array = array_map(function ($row) {
    return array(
        'info'  => $row['info'],
        'lat'   => $row['lat'],
        'lng'   => $row['lng'],
    );
}, $rows);

If you need indexes starting from 1 you should also add this line:

$array = array_combine(range(1, count($array)), $array);

Upvotes: 1

Kapil Sharma
Kapil Sharma

Reputation: 10427

Read the manual

Example taken from PHP manual

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);

Upvotes: 1

Related Questions