Grouping array elements based on a common string

I have the following code that captures two separate arrays, flips the last name and first name (also removes the comma), and outputs this:

Director: Burt and Bertie

Writer: Burt and Bertie

Manufacturer: Louise Knight

Manufacturer: Miles Wilkes

Producer: Andy Welch

Actor: Craig Parkinson

Actor: Camilla Rutherford

Actor: Paul Bhattarcharji

Actor: Ford Kiman

Actor: Morren Pug

Actor: Hannah Walters

DP: Lynda Hall

Cut: Matt Chodan

What I need to do is group similar groups in order to output something like this:

Director: Burt and Bertie

Writer: Burt and Bertie

Producer: Louise Knight, Miles Wilkes, Andy Welch

Actors: Craig Parkinson, Camille Rutherford, Paul Bhattarcharji, Ford Kiman, Morren Pug, Hannah Walters

DP: Lynda Hall

Cut: Matt Chodan

Current PHP code:

<?php $arrayname=explode(":::",$dwzXmlRec_1->GetFieldValue("PERSON_NAME")); $arraynamel=count($arrayname); $arrayrole=explode(":::",$dwzXmlRec_1->GetFieldValue("PERSON_FUNCTION")); $arrayrolel=count($arrayrole); $name = "Lastname, Firstname"; $names = explode(", ", $name); $name = $names[1] . " " . $names[0]; for($i=0;$i<$arrayrolel;$i++) { $names = explode(", ", $arrayname[$i]); $name = $names[1] . " " . $names[0]; echo $arrayrole[$i].': '.$name.'<br />'; } ?> 

UPDATE: there is only one question, the data is asked from the xml node, and since it is in the "how" array, this is one role that appears before another. For example, first โ€œActorโ€, then โ€œDirectorโ€. Is there an easy way to cancel it, so that the director comes first and then Cast? I added code to hide unwanted roles / peoples, as shown below:

 // print out the list of people in each role foreach($roles as $rolename => $people) { if ($rolename!="Cut" && $rolename!="Producer" && $rolename!="DP" && $rolename!="Writer"){ if($rolename=="Actor") { $rolename="Cast";}; echo $rolename . ": " . implode(", ", $people) . "<br />"; } } 
+4
source share
1 answer

I would build an array that maps role names to an array of people who filled this role. Maybe something like this:

 $roles = array(); for($i = 0; $i < $arrayrole1; $i++) { $names = explode(", ", $arrayname[$i]); $name = $names[1] . " " . $names[0]; // append the name to the array of people filling the role $roles[$arrayrole[$i]][] = $name; } // print out the list of people in each role foreach($roles as $rolename => $people) { echo $rolename . ": " . implode(", ", $people) . "<br />"; } 
+3
source

Source: https://habr.com/ru/post/1440181/


All Articles