What are the best practices for handling data retrieval and presentation in PHP to avoid complex nested loops and improve efficiency?

Complex nested loops can lead to inefficient data retrieval and presentation in PHP. To avoid this, it is recommended to use SQL queries with proper joins and filtering to retrieve the necessary data in a single query. Additionally, organizing the data into arrays or objects before presentation can help simplify the code and improve efficiency.

// Example of using SQL query with join to retrieve data efficiently

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');

// SQL query with join to retrieve data
$query = "SELECT users.name, orders.order_date, products.product_name 
          FROM users 
          JOIN orders ON users.id = orders.user_id 
          JOIN products ON orders.product_id = products.id";

$stmt = $pdo->query($query);

// Fetch data and organize into arrays or objects for presentation
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $data[] = $row;
}

// Display the data
foreach ($data as $row) {
    echo $row['name'] . ' made an order for ' . $row['product_name'] . ' on ' . $row['order_date'] . '<br>';
}