如何统计爆炸阵列

时间:2015-08-06 22:32:00

标签: php arrays

我的字符串如下:

244.53.66=1,53.646.77=1,666.534.23=5,664.521.64=3,535.777.54=2,533.886=5,22.153=5,643.786=2

我把它炸得像:

$string = "244.53.66=1,53.646.77=1,666.534.23=5,664.521.64=3,535.777.54=2,533.886=5,22.153=5,643.786=2";
    $array = explode(",", $string);
            $array2=array();
            for($i = 0; $i<count($array); $i++) 
            {
                array_push($array2, explode("=",$array[$i]));
            }

现在$ array2得到了这些值:

$array2[0][0] = "244.53.66";
$array2[0][1] = "1";
$array2[1][0] = "53.646.77";
$array2[1][1] = "1";

如何计算每种类型的所有值,例如:

2 x 1(两条记录的值为1),1x1(1条记录的值为1)itd。

我想将其存储为数组:

$array3[index] = "amount same values";
你能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

首先需要在单独的数组中获取ID,然后使用array_count_values计算ID的数量。

这是最终的代码:

<?php
$string = "244.53.66=1,53.646.77=1,666.534.23=5,664.521.64=3,535.777.54=2,533.886=5,22.153=5,643.786=2";
$array = explode(",", $string);
$array2=array();
for($i = 0; $i<count($array); $i++)
{
    array_push($array2, explode("=",$array[$i]));
}

$array3 = array();
//Iterate through array 2 to extract all IDs
for($i = 0; $i<count($array2); $i++)
{
   array_push($array3, $array2[$i][1]);
}
$vals = array_count_values($array3);
print_r($vals);
?>

哪个输出

Array
(
    [1] => 2
    [5] => 3
    [3] => 1
    [2] => 2
)

StackOverflow上的快乐编码!