/*
author: [email protected]
description: 交换数组中两个元素的位置,元素包括key和value,具体用法见下面的例子
*/
$arr = array(11=>‘a‘,22=>‘b‘,33=>‘c‘,44=>‘d‘);
$res = array_exchange($arr, 11 ,33);
//example:
echo ‘<pre>‘;print_r ($res);echo ‘</pre>‘;
function array_exchange($arr,$arg1,$arg2){
$r = range(0,count($arr)-1);
$res = $res_bak = array_combine($r,array_keys($arr));
$change = array($arg1,$arg2);
list($res[array_search($change[0],$res_bak)],$res[array_search($change[1],$res_bak)]) = array($change[1],$change[0]);
foreach ($res as $v){
$array[$v] = $arr[$v];
}
return $array;
}
时间: 2024-10-26 19:12:17