计算对象数组中有多少重复键?

时间:2018-02-14 09:04:59

标签: php arrays duplicates key

[
    {
        "playerId":3207,
        "playerName":"RyanGarbutt",
        "playerPos":"C",
        "playerApiId":"5079"
    },
    {
        "playerId":3238,
        "playerName":"Max Domi",
        "playerPos":"C",
        "playerApiId":"5412"
    },
    {
        "playerId":3240,
        "playerName":"AnthonyDuclair",
        "playerPos":"LW",
        "playerApiId":"5441"
    }
]

1→我想计算playerPos(C,LW)的出现次数? 2→如何获取格式如[{“c”:“2”},{“LW”:“1”}}

4 个答案:

答案 0 :(得分:0)

您可以使用array_reduce

$arr = '[{"playerId":3207,"playerName":"RyanGarbutt","playerPos":"C","playerApiId":"5079"},{"playerId":3238,"playerName":"Max Domi","playerPos":"C","playerApiId":"5412"},{"playerId":3240,"playerName":"AnthonyDuclair","playerPos":"LW","playerApiId":"5441"}]';
$arr = json_decode( $arr, true );

$result = array_reduce( $arr , function( $c, $v ) {
    isset( $c[ $v[ "playerPos" ] ] ) ? $c[ $v[ "playerPos" ] ]++ : $c[ $v[ "playerPos" ] ] = 1;
    return $c;
}, array() );


echo "<pre>";
print_r( $result );
echo "</pre>";

这将导致:

Array
(
    [C] => 2
    [LW] => 1
)

Doc:http://php.net/manual/en/function.array-reduce.php

答案 1 :(得分:0)

没有循环,条件和回调函数。

$arr = '[{"playerId":3207,"playerName":"RyanGarbutt","playerPos":"C","playerApiId":"5079"},{"playerId":3238,"playerName":"Max Domi","playerPos":"C","playerApiId":"5412"},{"playerId":3240,"playerName":"AnthonyDuclair","playerPos":"LW","playerApiId":"5441"}]';
$arr = json_decode( $arr, true );
$result = array_count_values(array_column($arr,"playerPos"));
print_r($result);

输出

    Array ( 
          [C] => 2 
          [LW] => 1 
)

工作示例 Demo

答案 2 :(得分:-1)

您可以尝试这样的事情:

1 /首先,创建两个var,用作“C”和“LW”出现的计数器:

$C  = 0;
$LW = 0;   

2 /使用foreach循环遍历数组并每次测试关键字“playerPos”的obj值是否等于“C”或“LW”,然后为你的计数器var添加+1:< / p>

foreach($array as $obj) {
    $test = $obj['playerPos'];
    if ($test == "C")
        $C++;
    else if ($test == "LW")
        $LW++;
}

3 /然后你需要检查每个var的值以知道出现次数。

这是你在找什么?

答案 3 :(得分:-1)

function unique_multidim_array($array, $key) {
    $temp_array = array();
    $i = 0;
    $key_array = array();

    foreach($array as $val) {
        if (!in_array($val[$key], $key_array)) {
            $key_array[$i] = $val[$key];
            $temp_array[$i] = $val;
        }
        $i++;
    }
    return $temp_array;
}

$data =
    '[{
    "playerId":3207,"playerName":"RyanGarbutt","playerPos":"C","playerApiId":"5079"},{
    "playerId":3238,"playerName":"Max Domi","playerPos":"C","playerApiId":"5412"},{
    "playerId":3240,"playerName":"AnthonyDuclair","playerPos":"LW","playerApiId":"5441"}]';

$data=json_decode($data,true);

$uniqueArray = unique_multidim_array($data,'playerPos');

print_r($uniqueArray);

print_r(count($uniqueArray));