PHP比较数组结果和过滤器

时间:2015-10-06 19:18:27

标签: php arrays

我有一个看起来像这样的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]if ((time_start >= 800) && (time_start <= 1800)) { cout << "How many minutes did your call last? "; cin >> minutes; cost = minutes * 0.40; cout << setprecision(2) << fixed << cost; system("pause"); keepgoing = false; } else if ((time_start < 800) && (time_start > 1800)) { cout << "How many minutes did your call last? "; cin >> minutes; cost = minutes * 0.25; cout << setprecision(2) << fixed << cost; system("pause"); keepgoing = false; } 中的值{{1}} 1}}来自数组的值?

3 个答案:

答案 0 :(得分:2)

您应该对数组进行排序

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 ......

答案 1 :(得分:1)

您可以使用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和按计数过滤(parent_id)&gt; 1

示例:

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

答案 2 :(得分:1)

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

  • 它永远是你的O(n)解决方案
  • 它保持您期望的相同数据结构
  • 不需要您合并多个筛选结果集。并合并数据。

////

Ticket