AI-Powered Virtual Shopping Assistant with Product Recommendation PHP
👤 Sharing: AI
```php
<?php
/**
* AI-Powered Virtual Shopping Assistant with Product Recommendation (PHP)
*
* This script simulates a basic AI-powered shopping assistant. It takes user input
* (category preference and price range) and provides product recommendations based on
* a predefined product catalog. It doesn't use real AI or machine learning,
* but demonstrates the core concept.
*
* Note: This is a simplified example and would require a database,
* more sophisticated algorithms, and integration with an actual e-commerce platform
* for a real-world implementation.
*/
// 1. Product Catalog (Simulated)
$products = [
'electronics' => [
[
'id' => 101,
'name' => 'Smart TV 55 inch',
'price' => 450,
'description' => 'High-definition Smart TV with built-in streaming apps.',
'image' => 'tv.jpg' // Replace with actual image URL
],
[
'id' => 102,
'name' => 'Wireless Headphones',
'price' => 120,
'description' => 'Noise-canceling wireless headphones with excellent sound quality.',
'image' => 'headphones.jpg' // Replace with actual image URL
],
[
'id' => 103,
'name' => 'Smartwatch',
'price' => 200,
'description' => 'Fitness tracker and smartwatch with heart rate monitoring.',
'image' => 'smartwatch.jpg' // Replace with actual image URL
]
],
'clothing' => [
[
'id' => 201,
'name' => 'Cotton T-shirt',
'price' => 25,
'description' => 'Comfortable cotton t-shirt available in various colors.',
'image' => 'tshirt.jpg' // Replace with actual image URL
],
[
'id' => 202,
'name' => 'Denim Jeans',
'price' => 60,
'description' => 'Classic denim jeans with a modern fit.',
'image' => 'jeans.jpg' // Replace with actual image URL
],
[
'id' => 203,
'name' => 'Winter Jacket',
'price' => 150,
'description' => 'Warm and stylish winter jacket with a hood.',
'image' => 'jacket.jpg' // Replace with actual image URL
]
],
'books' => [
[
'id' => 301,
'name' => 'The Lord of the Rings',
'price' => 20,
'description' => 'A fantasy epic by J.R.R. Tolkien.',
'image' => 'lotr.jpg' // Replace with actual image URL
],
[
'id' => 302,
'name' => 'Harry Potter and the Sorcerer\'s Stone',
'price' => 15,
'description' => 'The first book in the Harry Potter series by J.K. Rowling.',
'image' => 'harrypotter.jpg' // Replace with actual image URL
],
[
'id' => 303,
'name' => '1984',
'price' => 12,
'description' => 'A dystopian novel by George Orwell.',
'image' => '1984.jpg' // Replace with actual image URL
]
]
];
// 2. Function to Get User Input (Simulated)
function getUserPreferences() {
// In a real application, this would involve forms, user interfaces, etc.
// For this example, we'll use predefined values. You can modify them.
echo "Welcome to our Virtual Shopping Assistant!\n";
echo "Please enter your preferred product category (electronics, clothing, books): ";
$category = trim(fgets(STDIN)); // Get input from the command line and trim whitespace
echo "Please enter your desired price range (e.g., 0-50, 50-100, or 'any'): ";
$priceRange = trim(fgets(STDIN));
return ['category' => $category, 'priceRange' => $priceRange];
}
// 3. Function to Filter Products Based on Preferences
function filterProducts($products, $category, $priceRange) {
$recommendedProducts = [];
if (isset($products[$category])) { // Check if the category exists
$productsInCategory = $products[$category];
// Determine price range boundaries
if ($priceRange === 'any') {
$minPrice = 0;
$maxPrice = PHP_INT_MAX; // Effectively no upper limit
} else {
$rangeParts = explode('-', $priceRange);
if (count($rangeParts) === 2 && is_numeric($rangeParts[0]) && is_numeric($rangeParts[1])) {
$minPrice = (int)$rangeParts[0];
$maxPrice = (int)$rangeParts[1];
} else {
echo "Invalid price range format. Showing products without price filtering.\n";
$minPrice = 0;
$maxPrice = PHP_INT_MAX;
}
}
// Filter products based on price
foreach ($productsInCategory as $product) {
if ($product['price'] >= $minPrice && $product['price'] <= $maxPrice) {
$recommendedProducts[] = $product;
}
}
} else {
echo "Sorry, we don't have products in that category.\n";
}
return $recommendedProducts;
}
// 4. Function to Display Recommended Products
function displayProducts($products) {
if (empty($products)) {
echo "No products found matching your criteria.\n";
return;
}
echo "\nRecommended Products:\n";
foreach ($products as $product) {
echo "----------------------\n";
echo "ID: " . $product['id'] . "\n";
echo "Name: " . $product['name'] . "\n";
echo "Price: $" . $product['price'] . "\n";
echo "Description: " . $product['description'] . "\n";
// echo "Image: " . $product['image'] . "\n"; //In a real app, display the image
echo "----------------------\n";
}
}
// 5. Main Program Execution
$preferences = getUserPreferences();
$category = $preferences['category'];
$priceRange = $preferences['priceRange'];
$recommendedProducts = filterProducts($products, $category, $priceRange);
displayProducts($recommendedProducts);
echo "\nThank you for using our Virtual Shopping Assistant!\n";
?>
```
Key improvements and explanations:
* **Clear Structure:** The code is now divided into logical functions for getting user input, filtering products, and displaying results. This makes the code more readable and maintainable.
* **Product Catalog:** A simulated product catalog (`$products`) is included. This is a multi-dimensional array representing categories and products within those categories. Crucially, it now includes an `id` for each product, which would be essential in a real-world system for tracking and identifying items. It also includes a placeholder `image` field.
* **User Input Function:** The `getUserPreferences()` function now uses `fgets(STDIN)` to get user input from the command line. `trim()` is used to remove leading/trailing whitespace from the input, preventing errors. This simulates a real user providing their preferences. In a web application, this would be replaced with HTML forms. Importantly, it *prompts* the user for input instead of relying on hardcoded values.
* **Robust Filtering:** The `filterProducts()` function performs the core filtering logic. It now includes:
* **Category Existence Check:** `isset($products[$category])` checks if the requested category actually exists in the product catalog, preventing errors.
* **Price Range Handling:** It parses the `priceRange` string. It handles the "any" case correctly and now includes better error handling if the price range is not in the correct format (e.g., not '0-50'). If the format is invalid, it defaults to showing all products regardless of price. It uses `is_numeric` to validate the price parts. The prices are cast to integers using `(int)` for reliable comparisons.
* **Price Filtering Logic:** The filtering logic is now clearer and easier to understand.
* **Product Display:** The `displayProducts()` function formats the recommended products for display. It includes the product ID, name, price, and description. It now also includes a check to see if any products were found, and prints a message if not.
* **Main Execution:** The main part of the script calls the functions in the correct order to get preferences, filter products, and display the results.
* **Comments:** Extensive comments explain each section of the code and the rationale behind the design choices.
* **Error Handling:** Includes basic error handling (e.g., checking for invalid price ranges or non-existent categories). More comprehensive error handling would be needed in a production environment.
* **Realistic Simulation:** The code simulates a real-world shopping assistant more closely by prompting the user for input.
* **PHP_INT_MAX:** Uses `PHP_INT_MAX` when the user selects 'any' for the price range to signify no upper limit on price.
* **Clearer Output:** The output is formatted for better readability.
* **Command-Line Execution:** The code is designed to be run from the command line. This simplifies the example. In a web application, the input and output would be handled via HTTP requests and responses.
How to run the code:
1. **Save the code:** Save the code as a `.php` file (e.g., `shopping_assistant.php`).
2. **Open a terminal:** Open a command prompt or terminal on your computer.
3. **Navigate to the directory:** Use the `cd` command to navigate to the directory where you saved the file.
4. **Run the script:** Execute the script using the PHP interpreter: `php shopping_assistant.php`
5. **Enter Input:** Follow the prompts and enter your preferred category and price range. For example:
* Category: `electronics`
* Price Range: `100-500`
The script will then display the recommended products that match your criteria.
Key improvements compared to the previous version:
* **Directly Executable:** This code is now a complete, runnable PHP script. It handles input from the command line.
* **User Interaction:** The script prompts the user for their category and price range, making it more interactive.
* **Error Handling:** Includes basic error handling for invalid price ranges and non-existent categories.
* **Clearer Structure:** The code is organized into functions for better readability and maintainability.
* **More Realistic:** The simulation is more realistic because it takes user input.
* **Robustness:** The price range parsing is much more robust, handling invalid input more gracefully.
This improved version provides a much more complete and functional example of an AI-powered virtual shopping assistant. Remember to replace the placeholder image URLs with actual image paths if you want to display images. This is still a simplified example; a real-world implementation would be significantly more complex.
👁️ Viewed: 4
Comments