0

I have an array with values

Munnar, Cochin, Cochin, Cochin, Munnar, Cochin

I need to group the values as

Munnar(1), Cochin(3), Munnar(1), Cochin(1).

How can loop the array to get the desired output.

4

6 回答 6

4

你可以这样做:

<?
$arrAux = array('Munnar', 'Cochin', 'Cochin', 'Cochin', 'Munnar', 'Cochin');

$count = 0;
$previous = $arrAux[0];
foreach ($arrAux as $name){
  if ($previous === $name)
     $count++;
  else{
     echo "{$previous}({$count})";
     $previous = $name;
     $count = 1;
  }
}
//Print last item
echo "{$previous}({$count})";
?>

这应该可以完成工作,我认为您不想使用array_count_values. 此功能已在一分钟内完成,也许可以改进:)

于 2013-10-03T06:35:27.070 回答
1

尝试这个

  $arr = array('Munnar','Cochin','Cochin','Cochin','Munnar','Cochin');

$count = 0;
$previous=$arr[0]; 
$output = "";
 foreach($arr as $key=>$val)
{
    if($arr[$key]==$previous){
      $count++;
    }
   else
   {
      $output .= $previous."(".$count.")";
     $count=1;
     $previous= $arr[$key];
   }
} 

if($previous==$arr[count($arr)-1])
    $output.=$previous."(".$count.")";


echo $output;
于 2013-10-03T06:43:41.893 回答
0

编码:

<?php
$key = '';
$_n = array();
$_a = array('Munnar', 'Cochin', 'Cochin', 'Cochin', 'Munnar', 'Cochin');
foreach ($_a as $_1) {
    if ($key != $_1) {
        $idx = count($_n[$_1]);
        if ( isset($_n[$_1][$idx]) ) $idx += 1;
        $_n[$_1][$idx] = 1;
        $key = $_1;
    }
    else {
        $idx = count($_n[$_1]) -1;
        $_n[$_1][$idx] += 1;
    }
}


foreach ($_n as $k1=>$v1) {
    foreach ($v1 as $k2=>$v2) {
        echo 'Key: '.$k1.', Index:'.$k2.', Value:'.$_n[$k1][$k2].'<br/>';
    }
}
?>

结果

Key: Munnar Index:0 Value:1
Key: Munnar Index:1 Value:1
Key: Cochin Index:0 Value:3
Key: Cochin Index:1 Value:1

如果您需要问题中的确切顺序

Munnar(1), Cochin(3), Munnar(1), Cochin(1)

您可以使用上述方法并在最内层循环分配给一个新数组,如下所示:

$new_arr[] = array( $k1 => $_n[$k1][$k2] );

警告:确保开始键在第一次比较时总是不同的。

于 2013-10-03T06:48:43.747 回答
0
//print_r( array_count_values($yourarray));

$array=array_count_values($yourarray);

现在您可以遍历 $array 以获得所需的结果。

于 2013-10-03T06:36:52.493 回答
0

尝试这个

$array = array('Munnar','Cochin','Cochin','Cochin','Munnar','Cochin');
$vals = array_count_values($array);
echo 'No. of NON Duplicate Items: '.count($vals).'<br><br>';

  foreach($vals as $key=>$val){
echo $key."(".$val."),";
}

输出 :

Munnar(2),Cochin(4)
于 2013-10-03T06:37:30.580 回答
0

我不完全了解 PHP,但您可以尝试:

$array = array('Munnar','Cochin','Cochin','Cochin','Munnar','Cochin');

$prev = "";
$count = 0;

foreach($array as $key)
{
   if(empty($prev))
   {
       $prev = $key;
       $count = 1;
       continue;
   }

   if($prev === $key)
   {
      $count++;
   } else {
      echo "($prev)($count)";
      $prev = $key;
      $count = 1;
   }
}

echo "($prev)($count)";
于 2013-10-03T06:45:09.270 回答