从数组集中计算唯一值

时间:2019-06-03 10:32:41

标签: php arrays json array-unique

我有一个重复两次相同值的数组。我无法计算唯一值的总数。我的意思是电话号码是唯一的,并且当同一电话号码出现两次时,应该算作一个。

我已经尝试过使用array_unique方法。计算唯一值的总数。但是,它返回数组的总数。请帮助我解决此问题。

<div class="c100 p100 big dark green">
    <?php
    $url = 'xxxxxxxxxxxxxxxxxxxxxxxx'; // path to your JSON file
    //$url = 'data.json'; // path to your JSON file
    $data = file_get_contents($url); // put the contents of the file into a variable
    $characters = json_decode($data);
    $array = array_values(array_unique($characters, SORT_REGULAR));
    $i = 0;
    foreach ($array as $character) {
        $i++;
        ?>
    <?php }
    ?>
    <span>
    <?php
    echo $i;
    ?>
    </span>
    <div class="slice">
        <div class="bar"></div>
        <div class="fill"></div>
    </div>
</div>

JSON

[{"name":"xxxxxxxx","phoneNumber":"222223wssd","amount":50.00,"won":false,"date":"2019-05-01T02:35:38"},
{"name":"xxxxxxxx","phoneNumber":"222223wssd","amount":60.05,"won":false,"date":"2019-05-01T09:01:04"}]

期望值应计算唯一值,而不是数组中的所有值。

1 个答案:

答案 0 :(得分:1)

您可以使用array_column仅获取唯一的电话号码项。
此代码使数组与电话号码相关联,这意味着它将删除重复项。

然后我使用count()来计数项目数,而不是循环数组。

$json = '[{"name":"xxxxxxxx","phoneNumber":"222223wssd","amount":50.00,"won":false,"date":"2019-05-01T02:35:38"},
{"name":"xxxxxxxx","phoneNumber":"222223wssd","amount":60.05,"won":false,"date":"2019-05-01T09:01:04"}]';

$arr = json_decode($json, true);
$unique = array_column($arr, null, 'phoneNumber');

echo count($unique) . "\n";

var_dump($unique);

输出:

1 //count()
array(1) { // var_dump()
  ["222223wssd"]=>
  array(5) {
    ["name"]=>
    string(8) "xxxxxxxx"
    ["phoneNumber"]=>
    string(10) "222223wssd"
    ["amount"]=>
    float(60.05)
    ["won"]=>
    bool(false)
    ["date"]=>
    string(19) "2019-05-01T09:01:04"
  }
}

https://3v4l.org/A4p6d