【问题标题】:stop Array sort to remove duplicates停止数组排序以删除重复项
【发布时间】:2014-10-15 05:22:44
【问题描述】:

使用表达式引擎我有几个这样的循环:

{exp:channel:entries ........} <--- CMS Loop starts --->

 $data ="{event_day}.{event_month}.{event_year }"; // will output 19.21.2013 
      $titlu = htmlentities("{title}"); // string
      $link = "{adresa_externa}"; // website
      $arrContent3[strtotime($data)] = substr($data, 0, 5)." - ". "<a href='$link'> " . $titlu ."    </a>";
  {/exp:channel:entries} <--- cms loops ends --- >

在数组之后我们有以下代码:

<---- outputing in chronological order based on day year month --->
    <?php 
    ksort($arrContent3) ;
    echo html_entity_decode(implode("</li><li>", $arrContent));
    ?>

问题在于,如果存在 2 个日期完全相同的事物。列表中只会显示一个。

我不知道为什么:(

【问题讨论】:

  • 您正在使用 strtotime($data) 作为数组键。数组不能有重复的键。
  • 你对这个键有什么建议?我希望这些事件在同一天进入数组。 :(
  • 我不知道您使用密钥的目的,所以我无法预测更改它的后果。但是您知道问题出在哪里,因此您应该能够自行决定。
  • 我必须汇集来自不同来源的多个事件数组,然后根据日期和月份输出所有事件

标签: php arrays sorting duplicates date-sorting


【解决方案1】:

使用现有代码最简单的方法是在循环之前设置 $i = 0;,然后:

$arrContent3[strtotime($data).$i++] = substr($data, 0, 5)." - ". "<a href='$link'> " . $titlu ."    </a>";

虽然我不知道你是如何从$arrContent3$arrContent

【讨论】:

  • 虽然我不知道你是如何从 $arrContent3 转到 $arrContent。
  • 在你的模板代码中有$arrContent3[strtotime($data)],然后在PHP代码中有ksort($arrContent) ;。两个差异变量。
  • 我确实试过你的代码,但请记住我有多个像上面这样的数组。这是我在代码中的错误。我在输出 arrContent3 处编辑了 IS $arrContent3 ,但是如果我在每个数组中放置您建议的代码,则不再对整体结果进行排序。
  • 我想到了同样的 $i++ 事情,但(假设的)问题是,因为这是附加到一个整数,它几乎总是可以工作,但如果有日期导致时间戳具有不同的数字,则会失败位数(如 9... 和 10...)
【解决方案2】:

问题是,当您设置一个数组条目 $arrContent[strtotime($data)] 并且您已经有一个相同值的 $data 条目时,第二个会覆盖第一个。

所以不要给 $arrContent[strtotime($data)] 分配一个标量值,而是分配一个数组元素,

$arrContent[strtotime($data)][] = expression;

以与您相同的方式执行 ksort(),以按日期顺序获取它们,然后循环遍历数组叶子以生成一维数组,

foreach($arrContent as $arrDateContent) {
    foreach($arrDateContent as $content) {
        $arrContentAll[] = $content;
    }
}

然后你可以做回声,

echo html_entity_decode(implode("</li><li>", $arrContentAll));

编辑:

所以代码(来自原始问题)变为:

{exp:channel:entries ........} <--- CMS Loop starts --->

 $data ="{event_day}.{event_month}.{event_year }"; // will output 19.21.2013 
      $titlu = htmlentities("{title}"); // string
      $link = "{adresa_externa}"; // website
      $arrContent3[strtotime($data)][] = substr($data, 0, 5)." - ". "<a href='$link'> " . $titlu ."    </a>";
  {/exp:channel:entries} <--- cms loops ends --- >

然后是第二部分,

<---- outputing in chronological order based on day year month --->
    <?php 
    ksort($arrContent3) ;
    foreach($arrContent3 as $arrDateContent) {
        foreach($arrDateContent as $content) {
            $arrContentAll[] = $content;
        }
    }
    echo html_entity_decode(implode("</li><li>", $arrContentAll));
    ?>

【讨论】:

  • 如果我将代码添加到所有 3 个循环中,它会显示双打,但现在不再按日期和月份按时间顺序排列
  • @AgheorghieseiAndrei-Klauss 不确定你的意思,所以我在你的原始代码的编辑版本中添加了以更清楚我的意思。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 2012-03-10
  • 1970-01-01
  • 2021-11-12
  • 2021-01-27
  • 1970-01-01
  • 2016-01-24
相关资源
最近更新 更多