John Davidson

arrays - Parsing an Object with PHP

0 comments
Message:


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:


 $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?



My Answer:
"key1": "value1",
"key2": "value2",
"key3": "value3"
}

I want to parse this object in PHP and store the key-value pairs in an array. Here's how you can do it:

php
$json = '{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}';

$data = json_decode($json, true);

$array = [];

foreach ($data as $key => $value) {
$array[$key] = $value;
}

print_r($array);


This code will output:


Array
(
[key1] => value1
[key2] => value2
[key3] => value3
)


Now you have successfully parsed the object and stored the key-value pairs in an array in PHP.

Rate this post

5 of 5 based on 1393 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us