簡體   English   中英

在PHP中計算和構造唯一數組的更好方法

[英]Better way to count and construct unique array in PHP

我有以下代碼,需要花費很長時間才能執行。 有時它甚至會超時。

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

$totalownerships數組大小為52225 是否有更好的方法來編寫此代碼,以便執行它需要很長時間?

這將快得多,使用PHP的快速內置數組操作工具來消除循環中的數組搜索:

// 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);

有關更多PHP性能提示,請查看: PHP Bench

而不是使用O(n) in_array操作,我會使用O(1)鍵查找:

$totaltitles = array();
foreach ($totalownerships as $totalownership) {
    if (!isset($totaltitles[$totalownership['titleno']])) {
        $totaltitles[$totalownership['titleno']] = $totalownership['titleno'];
        $result['ownershipid'] .= " " . $totalownership['titleno'];
    }
}
$result['totalowns'] = count($totaltitles);

基本上,我們的想法是將您的唯一屬性用作數組鍵,這樣您就可以使用常量時間查找而不是線性查找。


如果你想采取(可能更慢)更漂亮的路線,你可以嘗試:

$uniques = array_unqiue(array_map(function($own) { 
    return $own['titleno']; 
}, $totalownerships));
$result = array(
    'ownershipid' => implode(' ', $uniques), 
    'totalowns' => count($uniques)
);

(正如Steven Moseley所說,如果您使用的是PHP 5.5,則可以使用array_column而不是該array_map調用。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM