在程序开发中数组一直是使用频率最高的数据类型之一。所以各种常用使用方法很多。今天分享一个二维数组取交集的问题。
数组一:(该数组仅为示例)
- array(4) {
- [0]=>{["c_id"]=> string(1) "1"
- ["info"]=> string(2) "ok"
- ["infocode"]=> string(5) "10000"
- ["locations"]=> string(32) "113.631375054254,34.745428602431" }
- [1]=>{["c_id"]=> string(1) "1"
- ["info"]=> string(2) "ok"
- ["infocode"]=> string(5) "10000"
- ["locations"]=> string(32) "113.631375054254,34.745428602431" }
- [2]=>{["c_id"]=> string(1) "2"
- ["info"]=> string(2) "ok"
- ["infocode"]=> string(5) "10000"
- ["locations"]=> string(32) "113.631375054254,34.745428602431" }
- [3]=>{["c_id"]=> string(1) "2"
- ["info"]=> string(2) "ok"
- ["infocode"]=> string(5) "10000"
- ["locations"]=> string(32) "113.631375054254,34.745428602431" }
- }
数组二:
- array(4) {
- [0]=>{["c_id"]=> string(1) "1"
- ["area"]=> string(2) "zhengzhou"
- ["age"]=> string(5) "23"
- ["sex"]=> string(32) "1" }
- [1]=>{["c_id"]=> string(1) "2"
- ["area"]=> string(2) "shanghai"
- ["age"]=> string(5) "19"
- ["sex"]=> string(32) "2" }
- [2]=>{["c_id"]=> string(1) "3"
- ["area"]=> string(2) "shanghai"
- ["age"]=> string(5) "19"
- ["sex"]=> string(32) "2" }
- [3]=>{["c_id"]=> string(1) "4"
- ["area"]=> string(2) "shanghai"
- ["age"]=> string(5) "19"
- ["sex"]=> string(32) "2" }
- }
实现功能:将数组二中c_id=1的信息加在数组一中c_id=1的信息后面,命名为staff,组成新数组。
- function arrcomb($arr1,$arr2){
- foreach($arr1 as $key1=>$value1){
- foreach($arr2 as $key2=>$value2){
- if($value1['c_id']==$value2['c_id']){
- $arr1["$key1"]['staff']=$value2;
- }
- }
- }
- return $arr1;
- }