如何用PHP将JSON值存入数组?提取JSON接口中total_value与car_id值到数组
Hey there! Let's tackle your two PHP + JSON questions with clear, hands-on examples. I'll break down both scenarios in detail below.
The go-to tool for this in PHP is the json_decode() function. By default, it converts JSON into a PHP object, but if you pass true as the second parameter, it'll spit out an associative array instead—perfect for your needs.
Example Code
Let's say you have a sample JSON string:
{ "user": "john_doe", "age": 30, "hobbies": ["coding", "hiking"] }
Here's how to convert it to a PHP array:
// Your JSON string $jsonString = '{"user": "john_doe", "age": 30, "hobbies": ["coding", "hiking"]}'; // Convert JSON to associative array $phpArray = json_decode($jsonString, true); // Now you can access values like any other array echo $phpArray['user']; // Outputs: john_doe print_r($phpArray['hobbies']); // Outputs: Array ( [0] => coding [1] => hiking )
If your JSON is a list (array) instead of an object, the process is identical—json_decode() will return a numeric-indexed PHP array automatically.
First, we need to fetch the API data, parse it, then extract the specific fields you need. I'll cover two common fetch methods: file_get_contents() (simple for basic cases) and cURL (more robust for complex scenarios).
Step 1: Assume a Realistic API Response Structure
Since you didn't provide the exact JSON, let's use a typical format for car data:
[ {"car_id": 101, "total_value": 25000, "model": "Toyota Camry"}, {"car_id": 102, "total_value": 32000, "model": "Honda Accord"}, {"car_id": 103, "total_value": 45000, "model": "Tesla Model 3"} ]
Step 2: Fetch, Parse, and Extract Fields
Option 1: Using file_get_contents() (Simple)
// Your API URL $apiUrl = 'https://example.com/your-car-api'; // Fetch the JSON data $jsonData = file_get_contents($apiUrl); // Handle fetch failures if ($jsonData === false) { die("Failed to retrieve data from the API"); } // Convert JSON to PHP array $carData = json_decode($jsonData, true); // Initialize empty arrays for your target fields $carIds = []; $totalValues = []; // Loop through each car entry to extract data foreach ($carData as $car) { // Add checks to avoid errors if fields are missing if (isset($car['car_id']) && isset($car['total_value'])) { $carIds[] = $car['car_id']; $totalValues[] = $car['total_value']; } } // View your results print_r($carIds); // Outputs: Array ( [0] => 101 [1] => 102 [2] => 103 ) print_r($totalValues); // Outputs: Array ( [0] => 25000 [1] => 32000 [2] => 45000 )
Option 2: Using cURL (More Robust)
If file_get_contents() is disabled on your server, cURL is a reliable alternative:
$apiUrl = 'https://example.com/your-car-api'; // Initialize cURL session $ch = curl_init($apiUrl); // Configure cURL options curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects if needed // Execute the request $jsonData = curl_exec($ch); // Handle cURL errors if (curl_errno($ch)) { die("cURL Error: " . curl_error($ch)); } // Close the cURL session curl_close($ch); // The rest matches Option 1: parse and extract fields $carData = json_decode($jsonData, true); $carIds = []; $totalValues = []; foreach ($carData as $car) { if (isset($car['car_id']) && isset($car['total_value'])) { $carIds[] = $car['car_id']; $totalValues[] = $car['total_value']; } }
Pro Tip
Always include isset() checks for your target fields—this prevents PHP warnings and makes your code resilient to unexpected API response changes.
内容的提问来源于stack exchange,提问作者pimienta

