所以,我看了几篇关于array_merge和array_unique的帖子,但是没有看到任何与我正在尝试的完全相同的内容。我假设解决方案是这样的:PHP - Merge-down multidimensional arrays by named key,除了我正在使用字符串,我还要找到重复的密钥,我认为这些密钥不起作用。
我有一个数组($ classagg),我用它来创建一个详细说明事件类的网页。我目前使用的代码是:
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>
";
}
一切都运作良好,但我有一些课程,其中两位主持人呈现同一个班级。系统被设置为CRM,所以很遗憾,我不能为两位演示者提供组合应用程序。
当前数组的简化版本可能如下:
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
)
)
我想合并数组0和2,保留标题,保留其中一个描述(最好是更长的描述),并保留两个名称。
我非常感谢任何帮助。
答案 0 :(得分:0)
$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;
}
}