【问题标题】:Combining Fields in an array based upon value根据值组合数组中的字段
【发布时间】:2013-01-02 02:41:14
【问题描述】:

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

非常感谢任何帮助。

【问题讨论】:

    标签: php


    【解决方案1】:
    $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;
      }
    }
    

    【讨论】:

    • 这在 if 行中添加了一个附加括号,效果很好。非常感谢
    • 你不会相信我一天有多少次想念这样的括号...现在编辑:-)
    猜你喜欢
    • 2015-04-23
    • 2015-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    相关资源
    最近更新 更多