Home  >  Article  >  php教程  >  用二维数组的某个唯一字段做key

用二维数组的某个唯一字段做key

WBOY
WBOYOriginal
2016-06-06 20:13:561584browse

$example=array(array('id'=4,'name'='hahah','age'=10),array('id'=3,'name'='hahahx','age'=10),array('id'=6,'name'='hahahf','age'=10),array('id'=9,'name'='hahahe','age'=10),); 初级阶段 function id_as_key($in){$out = array();foreach($in as $e)

$example=array(
array('id'=>4,'name'=>'hahah','age'=>10),
array('id'=>3,'name'=>'hahahx','age'=>10),
array('id'=>6,'name'=>'hahahf','age'=>10),
array('id'=>9,'name'=>'hahahe','age'=>10),
);

初级阶段

function id_as_key($in){
	$out = array();
	foreach($in as $e){
		$out[$e['id']]=$e;
	}
	return $out;
}

进阶

function id_as_key($in){
	$keys = array_column($in,'id');//php5.5以上才能使用该函数
	return array_combine($keys,$in);
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:php大小写敏感潜规则Next article:Poor Man PHP Profiler