So, I have looked at several posts regarding array_merge and array_unique, but haven't seen anything exactly like what I'm trying to do. I'm assuming the solution would be something like this: PHP - Merge-down multidimensional arrays by named key, except that I'm using strings and I'm also going to wind up with duplicate keys which I assume is not going to work.
I have an array ($classagg) that I'm using to create a webpage detailing classes for an event. The code I'm currently using is:
usort($classagg, function($a, $b) {
return strcmp($a['title'], $b['title']);
});
foreach($classagg as $out){
print "
<p>
<a class=\"education-class-list-title\" name=\"$out[presenter]\">$out[title]</a><br />
<span class=\"education-class-list-description\">$out[description]</span><br />
<span class=\"education-class-list-presenter\"> Presented by: <a href=\"/event/$out[eventType]/$out[eid]?qt-event=3#$out[presenter]\">$out[presenter]</a> </span>
</p>
";
}
Everything is working well, however I have some classes where two presenters are presenting the same class. The system is setup as a CRM, so unfortunately I can't have a combined application for both presenters.
A simplified version of the current array might like:
Array
(
[0] => Array
(
[title] => Class 1
[description] => This is a Class
[presenter] => John
)
[1] => Array
(
[title] => Class 2
[description] => This is a another class
[presenter] => Sue
)
[2] => Array
(
[title] => Class 1
[description] => Sally is presenting with John
[presenter] => Sally
)
)
I want to merge arrays 0 and 2, keeping the title, keeping one of the descriptions (preferably the longer one), and keep both of the names.
I greatly appreciate any help.
$newArray = array();
foreach( $array as $class ) {
if( isset( $newArray[$class['title']] ) ) {
$presenters = explode( ', ', $newArray[$class['title']]['presenter'] );
$presenters[] = $class['presenter'];
$newArray[$class['title']]['presenter'] = implode( ', ', $presenters );
$e = $newArray[$class['title']]['description'];
$n = $class['description'];
$newArray[$class['title']]['description'] = (strlen($n) > strlen($e) ? $n : $e);
}
else {
$newArray[$class['title']] = $class;
}
}