PHP数组限制相同类型(值)

时间:2014-11-23 12:11:17

标签: php arrays foreach

我在foreach循环中使用了多个数组。我想限制我在foreach中返回的类型字段值。然后我想通过评级值(最高的第一个)对foreach循环进行排序。

因此,在下面的示例中,最高评级和相同类型的限制为2(因此它应返回6个结果)。

array(3) {
["id"]=> 1
  ["type"]=> "type1"
  ["rating"]=> "8.0000"
}

array(3) {
  ["id"]=> 2
  ["type"]=> "type1"
  ["rating"]=> "10.0000"
}

array(3) {
  ["id"]=> 3
  ["type"]=> "type1"
  ["rating"]=> "6.5000"
}

array(3) {
  ["id"]=> 4
  ["type"]=> "type2"
  ["rating"]=> "6.0000"
}

array(3) {
  ["id"]=> 5
  ["type"]=> "type2"
  ["rating"]=> "10.0000"
}

array(3) {
  ["id"]=> 6
  ["type"]=> "type2"
  ["rating"]=> "6.5000"
}

array(3) {
  ["id"]=> 7
  ["type"]=> "type3"
  ["rating"]=> "6.0000"
}

array(3) {
  ["id"]=> 8
  ["type"]=> "type3"
  ["rating"]=> "10.0000"
}

array(3) {
  ["id"]=> 9
  ["type"]=> "type3"
  ["rating"]=> "6.5000"
}

4 个答案:

答案 0 :(得分:0)

也许你搜索array_unique()? http://php.net/manual/en/function.array-unique.php

答案 1 :(得分:0)

您可以使用array_filter过滤数组,如下所示:

$data = array(
    array(
        id => 1,
        type => "type1",
        rating => "8.0000"
    ),
    array(
        id => 2,
        type => "type1",
        rating => "10.0000"
    ),
    array(
        id => 3,
        type => "type1",
        rating => "6.5000"
    ),
    array(
        id => 4,
        type => "type2",
        rating => "6.0000"
    ),
    array(
        id => 5,
        type => "type2",
        rating => "10.0000"
    )
);

$type1 = array_filter(
    $data,
    function($elem) {
        return ($elem['type'] === 'type1');
    }
);

$type1仅包含type => "type1"的元素。

然后您可以使用uasort()对任何数组进行排序,以便通过您自己的比较函数对它们进行排序。如果您要按评分排序,则在使用floatval()进行比较时将评分转换为浮动。

答案 2 :(得分:0)

假设你的数组在$ myArr中,
您可以使用usort对数组进行排序:

<?php
usort($myArr, function($a, $b) {
    return @$a['rating'] - @$b['rating'];
});

并且由于你想要2而不是每种类型的1,你可以运行你的排序数组并保持计数以跟踪你有多少(你也可以用array_filter做类似的东西,但为了简单起见我和# 39;保持这种方式):

<?php
$finalArr = array();
$counts = array();
foreach ($myArr as $item) {
    if (!isset($counts[$item['type']]))
        $counts[$item['type']] = 0;
    $counts[$item['type']]++;
    if ($counts[$item['type']] < 2)
        $finalArr[] = $item;
}

print_r($finalArr);

答案 3 :(得分:0)

使用以下功能:

function sortedByRating($data) {
    $sorted = array();
    foreach($data as $subArray) {
        $sorted[$subArray['id']] = $subArray['rating'];
    }
    asort($sorted);
    $sorted = array_keys($sorted);
    $resultArray = array();
    foreach($data as $subArray) {
        $resultArray[array_search($subArray['id'], $sorted)] = $subArray;
    }
    ksort($resultArray);
    return array_values($resultArray);   
}

function getByType($data, $type) {
    return array_filter($data, function($subArray) use ($type){
        return $subArray['type'] === $type;
    });
}
相关问题