Search code examples
phphtmlsqlnested-loops

PHP - Queries and looping through data structure


I'm working on a project that has multi-tiered PHP tasks, one of which combines some MySQL queries with the PHP structures to print results to a text file. I have the connection, txt file creation, and queries completed and successfully functioning. My issues is in the PHP loop for the data structure and the nested loop to iterate/loop through the structure for the results and print them properly. The data structure loop is correct:

    $userQuery = "SELECT title, last_name, first_name
            FROM film_actor
            LEFT JOIN film f
            ON film_actor.film_id = f.film_id
            LEFT JOIN actor a
            ON a.actor_id = film_actor.actor_id
            ORDER BY title";

    $filmActors =fopen("FilmActors.txt","w");

    while ($row = mysqli_fetch_assoc($result))
      {
        $title = $row['title'];
        $last = $row['last_name'];
        $first = $row['first_name'];

        $filmActor["$title"][] = "$last".","."$first";
      }

The nested loop begins correctly for the key value, but every step I've used to loop and print results only prints the word 'array' rather than the elements. My SQL query is for a database that lists film names, and the actors in the films, so some of these films have 5+ actors listed. My goal is to print them to a text file like so: Film Name: Number of actors: Actor 1 last name, actor 1 first name; etc.

Here is what I"ve successfully started for the nested loop:

    while ($k_v = each($filmActor)) {
        foreach($filmActor as $k_v => $value) {
        //$k_v => $value;
        fputs($filmActors, "$title:$value\n");
    }

Solution

  • Easiest solution looks like this one:

    ...
    
    $filmActors = fopen("FilmActors.txt","w");
    $text = '';
    
    foreach ($filmActor as $film_title => $actors) {
        $text .= $film_title . ':' . count($actors) . ':' . implode(';', $actors) . PHP_EOL;
    }
    
    fwrite($filmActors, $text);
    fclose($filmActors);