## indexBy
根据指定的映射函数对值进行索引
例子:
~~~
$members=[
['id'=>1,'name'=>'小飞','sex'=>'男','age'=>28,'register_time'=>'2017-04-01 08:30:01'],
['id'=>1,'name'=>'小明','sex'=>'男','age'=>18,'register_time'=>'2017-04-01 08:30:01'],
['id'=>2,'name'=>'小红','sex'=>'女','age'=>18,'register_time'=>'2017-04-02 12:21:32'],
['id'=>3,'name'=>'小刚','sex'=>'男','age'=>16,'register_time'=>'2017-04-05 09:10:13'],
['id'=>4,'name'=>'小丽','sex'=>'女','age'=>19,'register_time'=>'2017-04-05 12:05:27'],
['id'=>5,'name'=>'小壮','sex'=>'男','age'=>21,'register_time'=>'2017-04-08 15:41:59'],
['id'=>6,'name'=>'小东','sex'=>'男','age'=>23,'register_time'=>'2017-04-01 08:30:01'],
];
$dataSource=Traversable::from($members);
$result=$dataSource->indexBy(function($m){
return $m['id']; //指定id为索引,如果有重复的值,保留第一条,去除其他重复值。
});
foreach ($result as $s){
dump($s);
}
~~~
打印结果:
第一条和第二条记录id相同,所以最后只保留第一条记录。
~~~
array:5 [▼
"id" => 1
"name" => "小飞"
"sex" => "男"
"age" => 28
"register_time" => "2017-04-01 08:30:01"
]
array:5 [▼
"id" => 2
"name" => "小红"
"sex" => "女"
"age" => 18
"register_time" => "2017-04-02 12:21:32"
]
array:5 [▼
"id" => 3
"name" => "小刚"
"sex" => "男"
"age" => 16
"register_time" => "2017-04-05 09:10:13"
]
array:5 [▼
"id" => 4
"name" => "小丽"
"sex" => "女"
"age" => 19
"register_time" => "2017-04-05 12:05:27"
]
array:5 [▼
"id" => 5
"name" => "小壮"
"sex" => "男"
"age" => 21
"register_time" => "2017-04-08 15:41:59"
]
array:5 [▼
"id" => 6
"name" => "小东"
"sex" => "男"
"age" => 23
"register_time" => "2017-04-01 08:30:01"
]
~~~