How can PHP be used to compare search terms with JSON data efficiently?
To efficiently compare search terms with JSON data in PHP, you can use the `json_decode` function to convert the JSON data into an associative array. Then, loop through the array to compare the search terms with the data. You can use functions like `strpos` or `preg_match` to perform the comparisons efficiently.
// Sample JSON data
$jsonData = '{"items": [{"name": "apple", "price": 1.99}, {"name": "banana", "price": 0.99}]}';
// Convert JSON data to associative array
$data = json_decode($jsonData, true);
// Search term
$searchTerm = "apple";
// Loop through the array to compare search terms
foreach ($data['items'] as $item) {
if (strpos($item['name'], $searchTerm) !== false) {
echo "Match found: " . $item['name'] . " - $" . $item['price'];
}
}