Grouping Array Items Based on Common String

arrays, grouping, php

Solution

I would build an array that maps role names to an array of people who filled that role. Possibly 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 />";
}

Problem

I have the following code which grabs two separate arrays, flips the surname and firstname (also removes the comma) and outputs this: Director: Bert & Bertie Writer: Bert & Bertie Producer: Louise Knight Producer: Miles Wilkes Producer: Andy Welch Actor: Craig Parkinson Actor: Camilla Rutherford Actor: Paul Bhattarcharjee Actor: Ford Kieman Actor: Maurren the Pug Actor: Hannah Walters DP: Lynda Hall Cut: Matt Chodan What I need to do is to group similar groups to output something like this: Director: Bert & Bertie Writer: Bert & Bertie Producer: Louise Knight, Miles Wilkes, Andy Welch Actors: Craig Parkinson, Camilla Rutherford, Paul Bhattarcharjee, Ford Kieman, Maurren the 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: Just one question, the data is set from an xml node, and since it's in array "as" is One role comes before another. For Example, 'Actor' comes first, then 'Director'. Is there any easy method to reverse it, so that Director comes first then Cast? I have added code to hide the unwanted roles/peoples see 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 />"; } } ```

Original source