-2

I have a DB column with a string as shown below

{"gpslev":"11","gsmlev":"4","hdop":"0.4","io16":"202847595","io175":"-1","io200":"0","io236":"0","io239":"0","io240":"0","io241":"65510","io247":"0","io251":"0","io252":"0","io253":"0","io254":"25","io310":"0","io66":"12299","io67":"4014","io68":"0","io69":"1","pdop":"0.5"}

I want to extract certain data from this string and echo it to a PHP page

I have used the following to no avail

function populateArrayFromString($string)
{
    $array = [];
    $pairs = explode(",", $string);
    foreach ($pairs as $pair) {
        list($key, $value) = explode(":", $pair);
        $arrayToReturn[trim($key, '"')] = trim($value, '"');
    }

    return $array;
}

$result = mysql_query("SELECT * FROM gs_objects WHERE imei = '354018115539821' ");
?>
<?php
while ($row = mysql_fetch_array($result)) {
    $data = populateArrayFromString($row['params']);
    ?>
    <?php echo $row['params']; ?>
    </br>
    <?php echo $data['io16']; ?>

If I echo the PARAMS coumn I see the whole string. If I echo the io16 in the param colum I get error

Notice: Undefined index: io16

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • https://dev.mysql.com/doc/refman/8.0/en/json.html will allow mysql to operate on the json blob , eg accessing elements out of it. – erik258 Aug 22 '21 at 15:09
  • You're assigning to `$arrayToReturn`, then returning `$array`. – Barmar Aug 22 '21 at 15:15
  • **Warning:** `mysql_*` extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, either the [mysqli](https://www.php.net/manual/en/book.mysqli.php) or [PDO_MySQL](https://www.php.net/manual/en/book.pdo.php) extension should be used. See also the [MySQL API Overview](https://www.php.net/manual/en/mysqlinfo.api.choosing.php) for further help while choosing a MySQL API. – Dharman Aug 22 '21 at 15:28
  • @Barmar Thanks I missed that. The change $arrayToReturn did the trick thank you – Maggie Ackermann Aug 22 '21 at 15:38

1 Answers1

4

use

$stmt = '{"gpslev":"11","gsmlev":"4","hdop":"0.4","io16":"202847595","io175":"-1","io200":"0","io236":"0","io239":"0","io240":"0","io241":"65510","io247":"0","io251":"0","io252":"0","io253":"0","io254":"25","io310":"0","io66":"12299","io67":"4014","io68":"0","io69":"1","pdop":"0.5"}';
$result = json_decode($stmt,true);
print_r($result);

and you will get and array

Array
(
    [gpslev] => 11
    [gsmlev] => 4
    [hdop] => 0.4
    [io16] => 202847595
    [io175] => -1
    [io200] => 0
    [io236] => 0
    [io239] => 0
    [io240] => 0
    [io241] => 65510
    [io247] => 0
    [io251] => 0
    [io252] => 0
    [io253] => 0
    [io254] => 25
    [io310] => 0
    [io66] => 12299
    [io67] => 4014
    [io68] => 0
    [io69] => 1
    [pdop] => 0.5
)

No nbeed to self poarse the json

nbk
  • 45,398
  • 8
  • 30
  • 47