[英]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;
这个答案比以前的答案需要更多的代码,但是由于以下原因,我认为这是一种更有效的解决方案:
////
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.