21,887
社区成员
发帖
与我相关
我的任务
分享
$testArr = array(
'php' => array(
'author' => 'allen',
'price' => 40,
),
'java' => array(
'author' => 'james',
'price' => 55,
),
'mysql' => array(
'author' => 'gates',
'price' => 30,
),
'html' => array(
'author' => 'bill',
'price' => 21,
)
);
foreach ($testArr as $v) {
$k[] = $v['price'];
}
array_multisort($k, SORT_DESC,$testArr);
print_r(array_slice($testArr,0,3));
$ar = array(
'php' => array(
'author' => 'allen',
'price' => 40,
),
'java' => array(
'author' => 'james',
'price' => 55,
),
'mysql' => array(
'author' => 'gates',
'price' => 30,
),
'html' => array(
'author' => 'bill',
'price' => 21,
),
);
function func($ar) {
$r = array(0);
foreach($ar as $k=>$v) {
if($v['price'] > min($r)) $r[$k] = $v['price'];
if(count($r) > 3) unset($r[array_search(min($r), $r)]);
}
}
check_speed(200, 'func', $ar);
func$testArr = array(
'php' => array(
'author' => 'allen',
'price' => 40,
),
'java' => array(
'author' => 'james',
'price' => 55,
),
'mysql' => array(
'author' => 'gates',
'price' => 30,
),
'html' => array(
'author' => 'bill',
'price' => 21,
)
);
/*** 应用回调函数 ***/
function func1($ar) {
uasort($ar, create_function('$a,$b', 'return $a["price"]>$b["price"];'));//价格升序,降序改成<
}
/*** 不使用回调函数 ***/
function func2($ar) {
foreach ($ar as $key => $row) {
$price[$key] = $row['price'];
}
array_multisort($price, SORT_ASC,$ar);
}
/*** 应用 php5.3 闭包 ***/
function func3($ar) {
array_multisort(array_map(function($v){return $v['price'];},$ar),$ar);
}
check_speed(200, 'func2', $testArr);
check_speed(200, 'func3', $testArr);
check_speed(200, 'func1', $testArr);
$testArr = array( 'php' => array( 'author' => 'allen', 'price' => 40, ), 'java' => array( 'author' => 'james', 'price' => 55, ), 'mysql' => array( 'author' => 'gates', 'price' => 30, ), 'html' => array( 'author' => 'bill', 'price' => 21, ) );
foreach ($testArr as $key=>$val)
$_testArr[$val['price']] = $val;
ksort($_testArr);
print_r($_testArr);
Array
(
[21] => Array
(
[author] => bill
[price] => 21
)
[30] => Array
(
[author] => gates
[price] => 30
)
[40] => Array
(
[author] => allen
[price] => 40
)
[55] => Array
(
[author] => james
[price] => 55
)
)
这是你期望得到的结果吗
foreach ($testArr as $key=>$val)
{
$val['key'] = $key;
$_testArr[$val['price'].$key] = $val;
}
ksort($_testArr);
$testArr = array();
foreach ($_testArr as $key=>$val)
{
unset($val['key']);
$testArr[$_testArr[$key]['key']] = $val;
}
print_r($testArr);