1

因此,我查看了几篇关于 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,保留标题,保留其中一个描述(最好是较长的),并保留两个名称。

我非常感谢任何帮助。

4

1 回答 1

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;
  }
}
于 2013-01-02T02:55:03.077 回答