0

I have an array with film information and the times when they will be shown in the cinema. each showing is another result, so one film can be in the array multiple times. I want to combine duplicate film entries into one and put all shows in another dimension in the new array. The formatting is this:

Array (
[title] => title
[synopsis] => synopsis
[poster] => poster
[cast] => cast
[director] => director
[length] => length
[rating] => rating
[datetime] => datetime )

Should be formatted into:

Array (
[title] => title
[synopsis] => synopsis
[poster] => poster
[cast] => cast
[director] => director
[length] => length
[rating] => rating
[datetime] => Array
( [0] => datetime0
  [1] => datetime1    
... )
)

Has anyone an idea how to combine it after "title" and put all entries for datetime in a new dimension. Thank for your help!

  • 1
    Are you fetching this data from a database? If yes, why don't you use `SELECT * from films GROUP BY title` ? – Nelson Rakson Apr 26 '20 at 16:34
  • @nelsonrakson good point, but the author may read this data from other types of DB. – Salim Ibrohimi Apr 26 '20 at 16:37
  • I am fetching them from a database. From two tables tbh. One table is the details of the film and the other one the date time for each show of the film. I could GROUP BY title, but then have to use foreach and fetch the shows for each film. – Yannick Fitch Apr 26 '20 at 22:22
  • Grouping this data is more directly and professionally done with sql. You will not need to do any iterated queries. You use `GROUP BY` and `GROUP_CONCAT()` in your SELECT. After you have created a comma-separate list of showtimes, when you want to present the data, just explode on the commas. This will also let you sort the result set based on the film name and generally pack much of the logic in your query -- where it will be easiest to read and manage. Next time that you ask a question, be sure to include your best coding attempt -- it is expected. – mickmackusa Apr 27 '20 at 08:40

1 Answers1

0

Suppose that title is unique (no two movies with the same title). Then this would work:

$newArray = [];
foreach ($array as $element) {
    if (array_key_exists($element['title'], $newArray)) {
        $newArray[$element['title']]['datetime'][] = $element['datetime'];
    } else {
        $element['datetime'] = [$element['datetime']];
        $newArray[$element['title']] = $element;
    }
}
$newArray = array_values($newArray);

However, as other comments pointed out, this is not an optimal solution, and you may want to think about the database structure or use something like CONCAT in SQL to return list of dates separated by a symbol, then use explode in PHP.