0

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.

Dharman
33.9k27 gold badges103 silver badges153 bronze badges
asked Nov 5, 2020 at 16:41
3
  • You meant article not aricle didn't you? Commented Nov 5, 2020 at 16:44
  • What is this doing $aricle = $["article"];? I yhink it should be $aricle = $row["article"]; and then put it into json decode Commented Nov 5, 2020 at 16:52
  • yes i forgot to adjust it thanks Commented Nov 5, 2020 at 16:57

3 Answers 3

1
$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);
answered Nov 5, 2020 at 16:50
Sign up to request clarification or add additional context in comments.

Comments

0

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
answered Nov 5, 2020 at 16:48

Comments

0

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

answered Nov 5, 2020 at 17:09

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.