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…

这个答案比前面的答案需要更多的代码,但我认为这是一个更有效的解决方案,原因如下:

  • 它将永远是您的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;
}

可以使用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和filter by count(parent_id)> 1

的例子:

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