数组冒泡排序 二维数组元素排序

/**************冒泡排序**/

$intarr = array(3,2,7,1,55,44);

function maopaoSort($str){
			
	  for($i=0;$i$str[$k]){
				$tmp = $str[$k-1];
				$str[$k-1] = $str[$k];
				$str[$k] = $tmp;
				}
			}
		}

      return $str; 
}

$res = maopaoSort($intarr);

print_r($res);//打印


/**
 * 对二维数组元素进行排序
 *
 */

$books = array(
	array('name'=>'php','price'=>100),
	array('name'=>'java','price'=>99),
	array('name'=>'mysql','price'=>200),
	array('name'=>'photoshop','price'=>20)
);

//方法一 :冒泡排序
function booksSort($books){
	for($i=0;$i$books[$j]['price']){
					$tmp_name = $books[$j-1]['name'];
					$tmp_price = $books[$j-1]['price'];
				
					$books[$j-1]['name'] = $books[$j]['name'];
					$books[$j-1]['price'] = $books[$j]['price'];
					
					$books[$j]['name'] = $tmp_name;
					$books[$j]['price'] = $tmp_price;
				}
		}
	}
	
	return $books;
}
print_r(booksSort($books));//打印

//方法二:
function booksSortTwo($arr){
	$tmp_arr = array();
	foreach($arr as $k=>$v){
			$tmp_arr[$k] = $v['price'];
		}
	asort($tmp_arr);
	foreach($tmp_arr as $kt=>$vt){
			$tmp_arr2[$kt] = $arr[$kt];
			$resarr[] = $tmp_arr2[$kt];
		}
	return $resarr;
	}

print_r(booksSortTwo($books));//打印


你可能感兴趣的:(数组冒泡排序 二维数组元素排序)