阿虎同学,要求将一个数组根据元素出现的次数来行进排列:
要求输出结果如下:
3出现5次
4出现2次
1出现2次

function getNumberOfCalculations($array,$orderby="desc"){

		$newArr =array();
		$count = 0;

		foreach ($array as $key => $value) {

			foreach ($array as $k => $v) {
				if($value == $v){
					$count++;
				}
			}

			if($count >0){
				$new['value'] = $value;
				$new['count'] = $count;
				array_push($newArr, $new) ;
			}
			unset($count);
		}

		$countArr  = array();
		$countArr2  = array();
		foreach ($newArr as $key1 => $value1) {
			$countArr[$value1['value']] = $value1['count'];
		}

		foreach ($countArr as $key2 => $value2) {
			$countA['value']=$key2;
			$countA['count']=$value2;
			$countArr2[] = $countA;
		}

		foreach ($countArr2 as $key3=>$value3){
		    $value4[$key3] = $value3['value'];
		    $count4[$key3] = $value3['count'];
		}

		if($orderby != 'desc'){
			array_multisort($count4,SORT_NUMERIC,SORT_ASC,$value4,SORT_STRING,SORT_ASC,$countArr2);
		}else{
			array_multisort($count4,SORT_NUMERIC,SORT_DESC,$value4,SORT_STRING,SORT_DESC,$countArr2);
		}

		return $countArr2;
}

$arr=array(1,2,3,4,23,44,0,45,3,0,3,1,2,3,4,23,44,0,45,3,0,3,45,9,123,6768,1232,99,9,99,111111,9999,99);
$array = getNumberOfCalculations($arr,"desc");

foreach ($array as $key => $value) {
	echo $value['value'] . "出现了:". $value['count'] ." 次</br>";
}

执行之后如下图:

php 根据某个字段对二维数组这个数组排序

Leave a Reply

电子邮件地址不会被公开。 必填项已用*标注

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="">

请选择吧!