explode和implode
explode分割字符串为数组
explode单词含义为:爆发,分解
implode将数组元素组合为字符串
implode单词含义为:内向爆炸,使压破
implode和explode都是二进制安全的,即不会将转义字符等特殊字符区别看待,认为其只是一个普通的字符
$r['path'] = 'a/b/c/d';
$r['explode'] = explode('/',$r['path']);
$r['implode'] = implode('//',$r['explode']);
$r['implode-nosparator'] = implode($r['explode']);
return $r;
{
"path": "a/b/c/d",
"explode": [
"a",
"b",
"c",
"d"
],
"implode": "a//b//c//d",
"implode-nosparator": "abcd"
}
链接
array_merge
实现需求:根据一张表得到用户的id和username数据,另一张表得到用户的id和password数据,现在根据user_id将两张表的数据结合起来,且顺序按照第二张表的来。
$r['data1'] = [['user_id'=>'1','username'=>'zhang'],['user_id'=>'2','username'=>'wang'],['user_id'=>'3','username'=>'li']];
$r['data2'] = [['user_id'=>'3','password'=>'li'],['user_id'=>'1','password'=>'zhang'],['user_id'=>'2','password'=>'wang']];
// 按照data2的顺序来排序,data1需要将共同元素设为主键
$r['data1-user_id'] = collect($r['data1'])->keyBy("user_id")->toArray();
// 遍历data2,根据主键合并data1
$r['data1+data2']=array_map(function($item) use ($r){
return array_merge($item,$r['data1-user_id'][$item['user_id']]);
},$r['data2']);
return $r;
// 作为排序依据的数据不需要变动,作为增加的数组需要将共同元素作为主键
// 之后遍历作为排序依据的数组,array_merge(遍历的排序依据数组中的数组,要合并的数组[遍历的排序依据数组中的数组[共同元素]])
{
"data1": [
{"user_id":"1","username":"zhang"}
{"user_id":"2","username":"wang"}
{"user_id":"3","username":"li"}
],
"data2": [
{"user_id":"3","password":"li"}
{"user_id":"1","password":"zhang"}
{"user_id":"2","password":"wang"}
],
"data1-user_id": {
"1": {
"user_id": "1",
"username": "zhang"
},
"2": {
"user_id": "2",
"username": "wang"
},
"3": {
"user_id": "3",
"username": "li"
}
},
"data1+data2": [
{"user_id":"3","password":"li","username":"li"}
{"user_id":"1","password":"zhang","username":"zhang"}
{"user_id":"2","password":"wang","username":"wang"}
]
}