php count array multidimensional with loop by value

时间:2015-07-17 12:34:57

标签: php multidimensional-array count

您好,感谢您的帮助,这是我的代码。

我有一个 number.txt 文件,如下所示:

5041655 5492272 1109
5041657 5492274 1109
5041656 5492273 1109
5041060 5491807 1102
5041656 5492273 1102
5036664 5486420 1101

我在php文件中加载 number.txt ,如下所示:

<?

$file = fopen("number.txt","r");
while(($get = fgetcsv($file, 1000, ",")) !== FALSE){

    $data = preg_split("/[\t]/", $get[0]);
    $username = $data[2];

    print_r($username);
}

?>

但我不知道如何打印如下:

number : 1109 is number1
number : 1109 is number2
number : 1109 is number3
number : 1102 is number1
number : 1102 is number2
number : 1101 is number1

谢谢。

3 个答案:

答案 0 :(得分:1)

试试这个

<?php
$array = array(
     1109,
     1109,
     1109,
     1102,
     1102,
     1101
);

for($i = 0; $i < count($array); $i++)
{
    echo "number : ".$array[$i]." is number".$i + 1 ."<br />";
}
?>

更新1

答案更新为您的问题。

<?php

$file = fopen("number.txt","r");

$i = 1;
while(($get = fgetcsv($file, 1000, ",")) !== FALSE)
{
    //$data = preg_split("/[\t]/", $get[0]);
    $data = explode(" ", $get[0]);

    $username = $data[2];

    //print_r($username);
    echo "number : $username is number".$i++."<br />";
}

?>

输出

The output after Update 1

更新2

<?php

$file = fopen("number.txt","r");

//$i = 1;
$numbers = array();
while(($get = fgetcsv($file, 1000, ",")) !== FALSE)
{
    //$data = preg_split("/[\t]/", $get[0]);
    $data = explode(" ", $get[0]);

    $numbers[] = $data[2];
    //$username = $data[2];

    //print_r($username);
    //echo "number : $username ";//$i++."<br />";
}

$numbers = array_count_values($numbers);
foreach($numbers as $key => $val)
{
    echo "number : $key found $val times<br />";
}

?>

更新2的输出

Output of update 2

最终答案

<?php

$file = fopen("number.txt","r");

$numbers = array();
while(($get = fgetcsv($file, 1000, ",")) !== FALSE)
{
    //$data = explode(" ", $get[0]);
    $data = preg_split("/[\t]/", $get[0]);

    $numbers[] = $data[2];
    $number = array_count_values($numbers);
    echo "number : $data[2] number ".$number[$data[2]]."<br />";
}

?>

最终输出

FINAL OUTPUT

答案 1 :(得分:0)

为了您的理解

 <?php
     $i = 1;
     foreach($array as $arr) {
       echo "<p>number : $arr[0] is number $i</p>";
       $i++;
     }

答案 2 :(得分:0)

在线之间阅读 - 我认为这就是你所追求的。 此解决方案“计算”相同值的数量,如果它们相同则递增值,或将计数器设置回1。

$array = array(
     Array ( 0 => 1109 ),
     Array ( 0 => 1109 ),
     Array ( 0 => 1109 ),
     Array ( 0 => 1102 ),
     Array ( 0 => 1102 ),
     Array ( 0 => 1101 )
);

$i = 1;

foreach($array as $a){

    foreach($a as $k => $v){

        $i = ($prevValue == $v) ? $i+1 : 1;

        echo "<br>number : $v is number $i";

        $prevValue = $v;

    }

}