How can JSON encoding and decoding be utilized to work with complex data structures in PHP?

JSON encoding and decoding can be utilized in PHP to work with complex data structures by converting PHP arrays or objects into a JSON string using json_encode() and vice versa by converting a JSON string into PHP arrays or objects using json_decode(). This allows for easy serialization and deserialization of data, making it simpler to store or transmit complex data structures.

// Example of encoding a complex data structure into JSON
$data = [
    'name' => 'John Doe',
    'age' => 30,
    'address' => [
        'street' => '123 Main St',
        'city' => 'Anytown'
    ]
];

$jsonData = json_encode($data);

// Example of decoding a JSON string into a PHP array
$jsonString = '{"name":"Jane Smith","age":25,"address":{"street":"456 Elm St","city":"Sometown"}}';

$decodedData = json_decode($jsonString, true);

// Accessing the decoded data
echo $decodedData['name']; // Output: Jane Smith
echo $decodedData['address']['city']; // Output: Sometown