简体   繁体   中英

How to get data in array format in from php mysql database

I have the following function in PHP, I am trying to get array in a specific format mentioned below but to no success, I am selecting a specific column in the mysql table than contains a json value like

{
    "lat": "-0.008668899503063161",
    "lng": "0.0025903204871857714"
}

This is the function

 function test()
    {

        $pdo = new PDO ("mysql:host=localhost;dbname=dbname","user", "secret");

        $statement=$pdo->prepare("SELECT test FROM merchants WHERE user_id = 1");
        $statement->execute();
        $data = array();
        while( $row = $statement->fetch(PDO::FETCH_ASSOC) )
        {
            $data[] = json_decode( $row['test'] );
        }


        return $data ;

    }

I am expecting the following result

['lat' => -0.008668899503063161,'lng' => 0.0025903204871857714,]

But this is what I keep getting

[{"lat":"-0.008668899503063161","lng":"0.0025903204871857714"}]

Don't push onto an array if you just want a single value.

function test()
{

    $pdo = new PDO ("mysql:host=localhost;dbname=dbname","user", "secret");

    $statement=$pdo->prepare("SELECT test FROM merchants WHERE user_id = 1");
    $statement->execute();
    row = $statement->fetch(PDO::FETCH_ASSOC) )
    if ($row) {
        $data = json_decode( $row['test'], true );
    } else {
        $data = null;
    }
    return $data ;
}

I managed to do it like this

 'merchants.location' =>
        [
              'lat' => $data['lat'],
              'lng' => $data['lng']

        ]

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