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

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

WBOY
Release: 2016-06-06 20:13:56
Original
1623 people have browsed it

$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),
);
Copy after login

初级阶段

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

进阶

function id_as_key($in){
	$keys = array_column($in,'id');//php5.5以上才能使用该函数
	return array_combine($keys,$in);
}
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template