How can one effectively retrieve data from a database in PHP and structure it into an array for easy access?

To effectively retrieve data from a database in PHP and structure it into an array for easy access, you can use the PDO (PHP Data Objects) extension to connect to the database, execute a query to fetch the data, and then iterate through the results to build an array.

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

// Prepare and execute a query
$stmt = $pdo->query('SELECT * FROM mytable');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Structure the data into an array for easy access
$data = [];
foreach ($results as $row) {
    $data[] = $row;
}

// Access the data in the array
foreach ($data as $row) {
    echo $row['column_name'] . '<br>';
}