如何在PHP中读取JSON ArrayList数据?报错问题求助
The error you're hitting comes down to a simple mix-up: you're trying to use PDO's fetch() method on decoded JSON data, but json_decode() returns a standard PHP object (or array), not a database query result set. The fetch() method only works with PDO statement objects, not JSON data.
Let's break down the problem and fix it step by step:
Your input JSON is an object containing an orderHistory array of products. When you run json_decode(file_get_contents("php://input")), you get a stdClass object where the orderHistory property holds your product list. Instead of using a while loop with fetch(), you need to loop directly through this array.
Corrected Code: Object Syntax
// Get posted JSON data and decode as an object $data = json_decode(file_get_contents("php://input")); // First, validate the input to avoid errors if (isset($data->orderHistory) && is_array($data->orderHistory)) { // Loop through each product in the orderHistory array foreach ($data->orderHistory as $product) { // Access individual product properties $name = $product->product_name; $price = $product->product_price; $id = $product->product_id; // Example: Output product details (adjust this to your needs) echo json_encode([ "message" => "Product processed", "product" => [ "id" => $id, "name" => $name, "price" => $price ] ]) . "\n"; } } else { // Handle cases where input is missing or malformed echo json_encode(["message" => "Invalid or missing order history data"]); }
Alternative: Array Syntax (if you prefer working with arrays)
Pass true as the second parameter to json_decode() to get an associative array instead of an object:
// Decode JSON as an associative array $data = json_decode(file_get_contents("php://input"), true); // Validate input if (isset($data['orderHistory']) && is_array($data['orderHistory'])) { foreach ($data['orderHistory'] as $product) { // Access product data using array keys $name = $product['product_name']; $price = $product['product_price']; $id = $product['product_id']; // Do something with the data (example output) echo "Processed product: $name (ID: $id, Price: $price)\n"; } } else { echo json_encode(["message" => "No valid order history found"]); }
Key Takeaways:
- Always validate input: Check if the expected properties exist (using
isset()) and are the correct type (likeis_array()fororderHistory). This prevents errors if the JSON is malformed or missing data. fetch()is for databases only: Useforeach()loops to iterate over JSON arrays, not PDO methods. PDO'sfetch()is meant for retrieving rows from database query results.
内容的提问来源于stack exchange,提问作者learner

