简体   繁体   中英

Convert JSON from MySQL to PHP

So i have this JSON in my MySQL Database

{
    "11011001": {
        "id": 11011001,
        "name": "Test",
        "price": 4,
        "inCart": 7
    }
}

Now i want to work with this data in PHP. I got the JSON by doing this in PHP:

$sql = "SELECT article FROM test WHERE id = '$id'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $aricle = $row["article"];
    } else {
        echo "Something went wrong";
    }

After that i did this which resulted in getting a JSON Array:

$tarray = json_decode($article, TRUE);

What can i do now to get the values from the JSON? For example i want the value of the price in a variable called $price.

$price = $tarray[11011001]['price'];

Or you can loop through the results if you have many articles

$tarray = json_decode($json,true);
        foreach ($tarray as $index => $item)
        {
            $price[] =  $item['price'];
        }
        var_dump($price);

Assuming you might have a collection of items, you can map the ids to prices with array_column.

<?php

$json =<<<JSON
{
    "11011001": {
        "id": 11011001,
        "name": "Test",
        "price": 4,
        "inCart": 7
    }
}
JSON;

$items = json_decode($json, TRUE);

$ids_prices = array_column($items, 'price', 'id');

var_export($ids_prices);

Output:

array (
    11011001 => 4,
)

Only one item, but you don't know the key up front?

if(count($items) === 1) {
    $item  = array_pop($items);
    $price = $item['price'];
}
echo $price;

Output:

4

First you have a sql injection, you must create a prepared query if you have data from users.

$sql = "SELECT article FROM test WHERE id = :id";
$query = $con->prepare($sql);
$query->bindValue(":id", $id);
$query->execute();
$result = $query->fetch();
if ($result) {
    // $article will be stdClass if json correct
    $article = json_decode($result['article']);
    $price = $article->price;
    // or $article = json_decode($result['article'], true);
    // $price = $article['price'];
    
}

Just an example

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