簡體   English   中英

PHP比較數組結果和過濾器

[英]PHP compare array results and filter

我有一個看起來像這樣的php數組:

Array(
[3086] => Array
    (
        [id] => 3086
        [note] => Make text larger
        [revision] => 1
        [noteParentId] => 1706
    )

[3087] => Array
    (
        [id] => 3087
        [note] => Make text larger
        [revision] => 2
        [noteParentId] => 1706
    )

[3085] => Array
    (
        [id] => 3085
        [note] => Enlarge this image
        [revision] => 1
        [noteParentId] => 1705
    )

[3084] => Array
    (
        [id] => 3086
        [note] => Another test note
        [revision] => 1
        [noteParentId] => 1704
    )

)

如果[noteParentId]的值相同(如何在[3086][3087]看到),如何從數組中刪除具有較低[revision]值的值呢?

您應該對數組進行排序

function mysort($a, $b){
    if ($a['revision'] >= $b['revision'])
        return 1;
    return -1;
}

然后將匹配的值存儲在另一個數組中

$arrResult = array();
usort($arrTest, "mysort");
foreach ($arrTest as $key=>$value){
    if (!isset($arrResult[$value['noteParentId']]))
        $arrResult[$value['noteParentId']] = array($key=>$value);
}

現在您需要清理$ arrResult ...

您可以使用array_filter函數http://php.net/manual/en/function.array-filter.php

例:

$parentId = 1706;
$filtered = array_filter($data, function($item) use ($parentId) { 
   return $item['noteParentId'] === $parentId; 
});

或者,如果您修改了sql查詢,則可以使用group by並按count(parent_id)> 1進行過濾

例:

SELECT noteParentId, count(*) FROM someTable GROUP BY noteParentId WHERE count(*) > 1;

這個答案比以前的答案需要更多的代碼,但是由於以下原因,我認為這是一種更有效的解決方案:

  • 它永遠是您的O(n)解決方案
  • 它保持您期望的相同數據結構
  • 它不需要您合並多個過濾的結果集。 並合並數據。

////

function filterOldRevisions($tasks) {

    $revisionHash = array();

    foreach ($tasks as $taskId => $task) {
        if (isset($revisionHash[$task['noteParentId']])) {
            $currentMaxRevision = $revisionHash[$task['noteParentId']];

            if ($task['revision'] > $revisionHash[$task['noteParentId']]) {
                //store the max revision for the parent in the hash
                $previousMaxId = $revisionHash[$task['noteParentId']]['id'];
                $revisionHash[$task['parentId']]  = $task;

                //remove the previous max revision
                unset($tasks[$previousMaxId]);
            } else {
                //remove lower revision
                unset($tasks[$taskId]);
            }
        } else {
            //always store the first task
            $revisionHash[$task['noteParentId']]  = $task;
        }
    }

    return $tasks;
}

暫無
暫無

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

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