如何使用PHP替换JSON中的值?求助:将指定JSON中SMART ID对应的UnitID修改为000000
Got it, let's break this down. The tricky part here is that your data field is actually a JSON string nested inside the main JSON object—so we can't just modify it directly. Here's a step-by-step solution in PHP that'll get the job done:
Step 1: Start with your original JSON
First, let's assign your raw JSON to a variable (I've cleaned up the escaped quotes for readability):
$originalJson = '{ "idline":"27", "idlock":"33", "data":"[ { \"ID\":\"SMART\", \"Sort\":\"1\", \"UnitID\":\"445678909\" }, { \"ID\":\"BOGLE\", \"Sort\":\"1\", \"UnitID\":\"57766446\" } ]" }';
Step 2: Decode the outer JSON
We'll convert the main JSON into a PHP associative array (using true as the second parameter in json_decode makes this easier to work with):
$outerArray = json_decode($originalJson, true);
Step 3: Decode the nested data string
The data value is a JSON string, so we need to decode that into a PHP array too:
$dataArray = json_decode($outerArray['data'], true);
Step 4: Find and update the "SMART" object
Loop through the dataArray to locate the item where ID equals "SMART", then set its UnitID to "000000" (we use a string here because numeric 000000 would automatically convert to 0):
foreach ($dataArray as &$item) { if ($item['ID'] === 'SMART') { $item['UnitID'] = '000000'; break; // No need to keep looping once we find our target } } unset($item); // Unset the reference to avoid unexpected behavior later
Step 5: Re-encode and update the outer array
Convert the modified dataArray back to a JSON string, then plug it back into the outer array:
$outerArray['data'] = json_encode($dataArray);
Step 6: Get your final modified JSON
Finally, encode the outer array back to a clean JSON string (adding JSON_PRETTY_PRINT makes it easier to read):
$finalJson = json_encode($outerArray, JSON_PRETTY_PRINT); echo $finalJson;
What the output will look like:
{ "idline": "27", "idlock": "33", "data": "[{\"ID\":\"SMART\",\"Sort\":\"1\",\"UnitID\":\"000000\"},{\"ID\":\"BOGLE\",\"Sort\":\"1\",\"UnitID\":\"57766446\"}]" }
A quick side note: If you prefer working with objects instead of arrays, you can skip the true parameter in json_decode and use object syntax (like $outerObject->data), but associative arrays are generally simpler for this kind of targeted manipulation.
内容的提问来源于stack exchange,提问作者H-ndi Santoso

