Anasde
Anasde

Reputation: 17

Getting value of php that is json_encode

Hello im trying to get the value of an element that is json_encoded.

  public function getDescription($noArticle){
  $stmt = $this->prepare("SELECT description FROM Inventaire WHERE noArticle = '{$noArticle}' ");
  $stmt->execute();
  $result = $stmt->fetchAll();
  return json_encode($result);

This returns me - > [{"description":"BMW M3"}] that is json_encoded.

I want to get only the "BMW M3"" part

I tried :

$allo = $allo->getDescription(1);
$test = json_decode($allo);
echo $test->{"description"};

not working if anyone could help me. Thanks

Upvotes: 0

Views: 95

Answers (3)

solikhay
solikhay

Reputation: 26

Since your variable $allo is an array of one element, you should get this first element then get your object like this:

$test[0]->description

Upvotes: 0

Buddy Christ
Buddy Christ

Reputation: 1396

Your json is an array of objects, you should use:

$allo = '[{"description":"BMW M3"}]';
$test = json_decode($allo);
echo $test[0]->description;

Upvotes: 1

Ben Hillier
Ben Hillier

Reputation: 2104

[{"description":"BMW M3"}] is an object within an array. So this should work:

echo $test[0]->description;

Upvotes: 0

Related Questions