dongmuyan5638 2013-06-17 02:16
浏览 16
已采纳

在PHP中计算和构造唯一数组的更好方法

I have the following code which takes rediculously long time to execute. Sometimes it even times out.

foreach ($totalownerships as $totalownership) {
    if (!in_array($totalownership['titleno'], $totaltitles)) {
        $result['totalowns'] += 1;
        $totaltitles[] = $totalownership['titleno'];
        $result['ownershipid'] = $result['ownershipid'] . " " .$totalownership['titleno'];
    }
}

The $totalownerships array size is 52225. Is there a better way of writing this code so that it doesn'e take long time to execute ?

  • 写回答

2条回答 默认 最新

  • dsstlsqt696435 2013-06-17 02:24
    关注

    This will be a lot faster, using PHP's speedy built-in array manipulation tools to eliminate array searches in a loop:

    // Add all titles to $totaltitles, for added speed
    foreach ($totalownerships as $totalownership) {
        $totaltitles[] = $totalownership['titleno'];
    }
    
    // For PHP 5.5+ you can use array_column() to get just the titleno field
    //$totaltitles = array_column($totalownership, 'titleno');
    
    // Use array_unique() to eliminate duplicate titles from $totaltitles
    array_unique($totaltitles);
    
    // Use count() to get a total count of $totaltitles
    $result['totalowns'] = count($totaltitles);
    
    // Use implode() for concatenation of title names
    $result['ownershipid'] .= " " . implode(" ", $totaltitles);
    

    For more PHP performance tips, check: PHP Bench

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 基于52单片机的酒精浓度检测系统加继电器和sim800
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答