简体   繁体   中英

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.

Read the manual

Example taken from PHP manual

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

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);
   $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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM