Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parsing an Object with PHP

I have the following format:

{ "_id" : { "$oid" : "61f41a529210000060005487" }, "number" : "3", "name" : "Honduras", "description" : "1500m height farming, price per 200gr", "price" : 7, "stock" : 10, "stars" : "Rated with 4.0 stars by users." }

I need to parse a few entries like the above in PHP. I am using foreach for that purpose. Everything except {"_id": {"$oid": … }} field seems to be parsed correctly. I get the following error:

Fatal error: Uncaught TypeError: Cannot access offset of type string on string

PHP script:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 $products = json_encode($cursor['products']);
 $products = json_decode($products, true) ;
 foreach ($products as $product) {
      $stringID = (string)$product['_id'];
      echo '<tr>';
           echo '<td>' . $stringID . '</td>';
           echo '<td>' . $product['number'] . '</td>';
           echo '<td>' . $product['name'] . '</td>';
           echo '<td>' . $product['description'] . '</td>'; 
           echo '<td>' . $product['price'] . '</td>'; 
           echo '<td>' . $product['stock'] . '</td>'; 
           echo '<td>' . $product['stars'] . '</td>';
       echo '</tr>';
 }

I have tried many solutions can’t parse it though. Any suggestions?

>Solution :

$product is a string, not an object. You should json_decode($product) before to access to properties.

foreach ($products as $product) 
{
    $product = json_decode($product);    // << decode here
    $stringID = $product['_id']['$oid']; // << access to ID

    // echo row :
    echo '<tr>';
         echo '<td>' . $stringID . '</td>';
         echo '<td>' . $product['number'] . '</td>';
         echo '<td>' . $product['name'] . '</td>';
         echo '<td>' . $product['description'] . '</td>'; 
         echo '<td>' . $product['price'] . '</td>'; 
         echo '<td>' . $product['stock'] . '</td>'; 
         echo '<td>' . $product['stars'] . '</td>';
     echo '</tr>';
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading