array1 = array(1 => a, 2 => a, 3 => a, 4 => b, 5 => b, 6 => c);
我希望以下列格式显示此数组:
一个
1
2
3
b
4
5
ç
6
答案 0 :(得分:5)
这将完成这项工作
$array = array(1=>'a',2=>'a',3=>'a',4=>'b',5=>'b',6=>'c');
$occurances = array_count_values($array);
foreach ($occurances as $key => $value) {
echo "$key".implode("",array_keys($array, $key));
}
注意:这将在线打印结果。如果要显示新编辑中显示的结果,请按以下步骤更改代码
$occurances = array_count_values($array);
$str = "";// modification starts here
foreach ($occurances as $key => $value) {
$finds = $key."<br/>".implode("<br/>",array_keys($array, $key));
$str .= ($str=="")?$finds:"<br/>".$finds;
}
echo $str;
array_count_values()从数组中返回值的关联数组作为键,并将其计数作为值。 link
array_keys()将从数组中返回键。您可以使用可选的search_value来仅获取该值的键。了解有关array_keys()here
的更多信息答案 1 :(得分:3)
$array1 = array(1 => 'a', 2 => 'a', 3 => 'a', 4 => 'b', 5 => 'b', 6 => 'c');
$new_array = array();
foreach($array1 as $key=>$val)
{
$new_array[$val][] = $key;
}
$string = '';
foreach($new_array as $key=>$val)
{
$string .= $key."\n".implode("\n",$val)."\n";
}
echo $string;