├── example
├── arrayTest.php
├── pf_set.php
├── pf_array_last.php
├── pf_array_first.php
├── pf_array_where.php
├── pf_get.php
├── pf_date.php
├── pf_exists.php
├── pf_array_depth.php
├── pf_array_flatten.php
├── pf_array_unique.php
├── pf_arr_sort.php
├── pf_array_insert.php
├── pf_array_diff_both.php
├── pf_array_shuffle.php
├── pf_rand_weighted.php
├── pf_del_val.php
├── pf_rand_val.php
├── pf_tree.php
├── pf_get_tree.php
├── pf_key_exists.php
├── pf_array_col.php
├── pf_obj_arr.php
├── pf_filter_keys.php
├── pf_deep_in_array.php
├── pf_array_rand_by_weight.php
├── README.md
└── pf_arr_group_by.php
├── .gitignore
├── phpunit.xml
├── tests
└── tests
│ ├── BaseTest.php
│ └── Test.php
├── composer.json
├── src
├── PFarr.php
└── build
│ ├── PFArrToCsv.php
│ ├── PFDateArr.php
│ ├── PFArrFormat.php
│ ├── PFArrCheck.php
│ └── Base.php
├── README.md
└── LICENSE
/example/arrayTest.php:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | .DS_Store
3 | /vendor
4 | composer.lock
5 | /attachment
6 | /app
7 | /config
8 | /storage
--------------------------------------------------------------------------------
/phpunit.xml:
--------------------------------------------------------------------------------
1 |
2 |
';
38 |
39 | PFarr::dd(PFarr::pf_del_val($array1,[1,2,3]));
40 | PFarr::dd(PFarr::pf_del_val($array2,[6,10]));
--------------------------------------------------------------------------------
/example/pf_rand_val.php:
--------------------------------------------------------------------------------
1 | _/___.' >'"".
23 | * | | : `- \`.;`\ _ /`;.`/ - ` : | |
24 | * \ \ `-. \_ __\ /__ _/ .-` / /
25 | * ========`-.____`-.___\_____/___.-`____.-'========
26 | * `=---='
27 | * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
28 | * 佛祖保佑 永无BUG 永不修改
29 | *
30 | */
31 | require __DIR__ . '/../vendor/autoload.php';
32 |
33 | use pf\arr\PFarr;
34 |
35 | $arr = [
36 | ['name'=>'TOP1','cid'=>0,'id'=>1],
37 | ['name'=>'TOP1','cid'=>1,'id'=>20],
38 | ['name'=>'TOP1','cid'=>0,'id'=>2],
39 | ['name'=>'TOP1','cid'=>2,'id'=>40],
40 | ['name'=>'TOP1','cid'=>2,'id'=>5],
41 | ];
42 |
43 | PFarr::dd(PFarr::pf_rand_val($arr,2));
44 |
--------------------------------------------------------------------------------
/example/pf_tree.php:
--------------------------------------------------------------------------------
1 | _/___.' >'"".
23 | * | | : `- \`.;`\ _ /`;.`/ - ` : | |
24 | * \ \ `-. \_ __\ /__ _/ .-` / /
25 | * ========`-.____`-.___\_____/___.-`____.-'========
26 | * `=---='
27 | * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
28 | * 佛祖保佑 永无BUG 永不修改
29 | *
30 | */
31 |
32 | require __DIR__ . '/../vendor/autoload.php';
33 |
34 | use pf\arr\PFarr;
35 |
36 | $arr = [
37 | ['name'=>'TOP1','cid'=>0,'id'=>1],
38 | ['name'=>'TOP1','cid'=>1,'id'=>20],
39 | ['name'=>'TOP1','cid'=>0,'id'=>2],
40 | ['name'=>'TOP1','cid'=>2,'id'=>40],
41 | ['name'=>'TOP1','cid'=>2,'id'=>5],
42 | ];
43 |
44 | PFarr::dd(PFarr::pf_tree($arr,0,'cid'));
--------------------------------------------------------------------------------
/example/pf_get_tree.php:
--------------------------------------------------------------------------------
1 | _/___.' >'"".
23 | * | | : `- \`.;`\ _ /`;.`/ - ` : | |
24 | * \ \ `-. \_ __\ /__ _/ .-` / /
25 | * ========`-.____`-.___\_____/___.-`____.-'========
26 | * `=---='
27 | * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
28 | * 佛祖保佑 永无BUG 永不修改
29 | *
30 | */
31 |
32 | require __DIR__ . '/../vendor/autoload.php';
33 |
34 | use pf\arr\PFarr;
35 |
36 | $arr = [
37 | ['name'=>'TOP1','cid'=>0,'id'=>1],
38 | ['name'=>'TOP1','cid'=>1,'id'=>20],
39 | ['name'=>'TOP1','cid'=>0,'id'=>2],
40 | ['name'=>'TOP1','cid'=>2,'id'=>40],
41 | ['name'=>'TOP1','cid'=>2,'id'=>5],
42 | ];
43 |
44 | PFarr::dd(PFarr::pf_get_tree($arr,0,'cid'));
--------------------------------------------------------------------------------
/example/pf_key_exists.php:
--------------------------------------------------------------------------------
1 | _/___.' >'"".
23 | * | | : `- \`.;`\ _ /`;.`/ - ` : | |
24 | * \ \ `-. \_ __\ /__ _/ .-` / /
25 | * ========`-.____`-.___\_____/___.-`____.-'========
26 | * `=---='
27 | * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
28 | * 佛祖保佑 永无BUG 永不修改
29 | *
30 | */
31 | require __DIR__ . '/../vendor/autoload.php';
32 |
33 | use pf\arr\PFarr;
34 |
35 | $arr = [
36 | 'name'=>'pfinal',
37 | 'sex' =>12,
38 | 'ADDRESS' =>'上海',
39 | 'def'=>[
40 | 'a'=>'img',
41 | 'size'=>'12',
42 | 'pfinal'=>[
43 | 'pf'=>'pf社区'
44 | ]
45 | ]
46 | ];
47 |
48 | PFarr::dd(PFarr::pf_key_exists($arr,'pf'),0);
--------------------------------------------------------------------------------
/example/pf_array_col.php:
--------------------------------------------------------------------------------
1 | _/___.' >'"".
23 | * | | : `- \`.;`\ _ /`;.`/ - ` : | |
24 | * \ \ `-. \_ __\ /__ _/ .-` / /
25 | * ========`-.____`-.___\_____/___.-`____.-'========
26 | * `=---='
27 | * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
28 | * 佛祖保佑 永无BUG 永不修改
29 | *
30 | */
31 |
32 | require __DIR__ . '/../vendor/autoload.php';
33 |
34 | use pf\arr\PFarr;
35 |
36 | $records = [
37 | [
38 | 'city' => '上海',
39 | 'age' => 18,
40 | 'name' => '马二'
41 | ],
42 | [
43 | 'city' => '上海',
44 | 'age' => 20,
45 | 'name' => '翠花'
46 | ]
47 | ];
48 |
49 | PFarr::dd(PFarr::pf_array_col($records, 'city'));
--------------------------------------------------------------------------------
/example/pf_obj_arr.php:
--------------------------------------------------------------------------------
1 | _/___.' >'"".
23 | * | | : `- \`.;`\ _ /`;.`/ - ` : | |
24 | * \ \ `-. \_ __\ /__ _/ .-` / /
25 | * ========`-.____`-.___\_____/___.-`____.-'========
26 | * `=---='
27 | * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
28 | * 佛祖保佑 永无BUG 永不修改
29 | *
30 | */
31 |
32 | require __DIR__ . '/../vendor/autoload.php';
33 |
34 | use pf\arr\PFarr;
35 |
36 | class obj
37 | {
38 |
39 | }
40 |
41 | $obj = new obj();
42 | $obj->body = 'another post';
43 | $obj->id = 21;
44 | $obj->approved = true;
45 | $obj->favorite_count = 1;
46 | $obj->status = NULL;
47 | //echo json_encode($obj);
48 | PFarr::dd(PFarr::pf_obj_arr($obj));
--------------------------------------------------------------------------------
/example/pf_filter_keys.php:
--------------------------------------------------------------------------------
1 | _/___.' >'"".
23 | * | | : `- \`.;`\ _ /`;.`/ - ` : | |
24 | * \ \ `-. \_ __\ /__ _/ .-` / /
25 | * ========`-.____`-.___\_____/___.-`____.-'========
26 | * `=---='
27 | * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
28 | * 佛祖保佑 永无BUG 永不修改
29 | *
30 | */
31 |
32 | require __DIR__ . '/../vendor/autoload.php';
33 |
34 | use pf\arr\PFarr;
35 |
36 | $arr = [
37 | 'name'=>'pfinal',
38 | 'sex' =>12,
39 | 'ADDRESS' =>'上海',
40 | 'def'=>[
41 | 'a'=>'img',
42 | 'size'=>'12',
43 | 'pfinal'=>[
44 | 'pf'=>'pf社区'
45 | ]
46 | ]
47 | ];
48 |
49 | PFarr::dd(PFarr::pf_filter_keys($arr,['ADDRESS','pfinal']));
--------------------------------------------------------------------------------
/example/pf_deep_in_array.php:
--------------------------------------------------------------------------------
1 | _/___.' >'"".
23 | * | | : `- \`.;`\ _ /`;.`/ - ` : | |
24 | * \ \ `-. \_ __\ /__ _/ .-` / /
25 | * ========`-.____`-.___\_____/___.-`____.-'========
26 | * `=---='
27 | * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
28 | * 佛祖保佑 永无BUG 永不修改
29 | *
30 | */
31 |
32 | require __DIR__ . '/../vendor/autoload.php';
33 |
34 | use pf\arr\PFarr;
35 |
36 | $arr = [
37 | 'name' => 'pfinal',
38 | 'sex' => 12,
39 | 'ADDRESS' => '上海',
40 | 'def' => [
41 | 'a' => 'img',
42 | 'size' => '12',
43 | 'pfinal' => [
44 | 'pf' => 'pf社区'
45 | ]
46 | ]
47 | ];
48 |
49 | PFarr::dd(PFarr::pf_deep_in_array($arr, 'pf社区'),0);
--------------------------------------------------------------------------------
/example/pf_array_rand_by_weight.php:
--------------------------------------------------------------------------------
1 | _/___.' >'"".
23 | * | | : `- \`.;`\ _ /`;.`/ - ` : | |
24 | * \ \ `-. \_ __\ /__ _/ .-` / /
25 | * ========`-.____`-.___\_____/___.-`____.-'========
26 | * `=---='
27 | * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
28 | * 佛祖保佑 永无BUG 永不修改
29 | *
30 | */
31 | require __DIR__ . '/../vendor/autoload.php';
32 |
33 | use pf\arr\PFarr;
34 |
35 | $arr = [
36 | ['id' => 10, 'value' => 1],
37 | ['id' => 11, 'value' => 12],
38 | ['id' => 12, 'value' => 11],
39 | ['id' => 13, 'value' => 10],
40 | ['id' => 14, 'value' => 1],
41 | ['id' => 15, 'value' => 9],
42 | ['id' => 16, 'value' => 1],
43 | ];
44 |
45 | PFarr::dd(PFarr::pf_array_rand_by_weight($arr));
--------------------------------------------------------------------------------
/tests/tests/Test.php:
--------------------------------------------------------------------------------
1 | _/___.' >'"".
23 | * | | : `- \`.;`\ _ /`;.`/ - ` : | |
24 | * \ \ `-. \_ __\ /__ _/ .-` / /
25 | * ========`-.____`-.___\_____/___.-`____.-'========
26 | * `=---='
27 | * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
28 | * 佛祖保佑 永无BUG 永不修改
29 | *
30 | */
31 |
32 | namespace tests;
33 |
34 |
35 | use pf\arr\PFarr;
36 | use PHPUnit\Framework\TestCase;
37 |
38 | class Test extends TestCase
39 | {
40 | public function testArrayExists()
41 | {
42 | $data = [
43 | 'k0' => 'v0',
44 | 'k1' => [
45 | 'k1-1' => 'v1-1'
46 | ],
47 | 'complex_[name]_!@#$&%*^' => 'complex',
48 | 'k2' => 'string'
49 | ];
50 | $this->assertEquals(true,PFarr::pf_exists('[k1][k1-1]',$data),'元素不在数组中');
51 | $this->assertEquals(true,PFarr::pf_exists('k1',$data),'元素不在数组中');
52 | $this->assertEquals(true,PFarr::pf_exists('k2',$data),'元素不在数组中');
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/example/README.md:
--------------------------------------------------------------------------------
1 | # 例子:
2 |
3 | - pf_exists() 判断数组中某个键有木有值
4 |
5 | > 例子: [pf_exists()](./pf_exists.php);
6 |
7 | - pf_arr_group_by() 通过指定值给数组分组
8 |
9 | > 例子: [pf_arr_group_by()](./pf_arr_group_by.php);
10 |
11 | - pf_del_val() 移除数组中的某段值
12 |
13 | > 例子: [pf_del_val()](./pf_del_val.php)
14 |
15 | - get() 点语法获取数组中的某个值
16 |
17 | > 例子: [get()](pf_get.php)
18 |
19 | - pf_key_exists() 多维数组检测键是否存在
20 |
21 | > 例子: [pf_key_exists()](.pf_key_exists.php)
22 |
23 | - pf_filter_keys() 数组元素过滤
24 |
25 | > 例子: [pf_filter_keys()](./pf_filter_keys.php)
26 |
27 | - pf_arr_sort() 多维数组排序
28 |
29 | > 例子: [pf_arr_sort()](./pf_arr_sort.php)
30 |
31 | - pf_tree() 二级获取树形结构
32 |
33 | > 例子:[pf_tree()](./pf_tree.php)
34 |
35 | - pf_get_tree() 多级获取树形结构
36 |
37 | > 例子:[pf_get_tree()](./pf_get_tree.php)
38 |
39 | - pf_array_unique() 数组去重
40 |
41 | > 例子:[pf_array_unique()](./pf_array_unique.php)
42 |
43 | - pf_array_depth() 数组维度检测
44 |
45 | > 例子:[pf_array_depth()](./pf_array_depth.php)
46 |
47 | - pf_array_col() 获取数组指定的列
48 |
49 | > 例子:[pf_array_col()](./pf_array_col.php)
50 |
51 | - pf_obj_arr() 对象转数组
52 |
53 | > 例子:[pf_obj_arr()](./pf_obj_arr.php)
54 |
55 | - pf_array_flatten() 将多维折叠数组变为一维
56 |
57 | > 例子:[pf_array_flatten()](./pf_array_flatten.php)
58 |
59 | - pf_array_rand_by_weight() 根据权重获取随机区间返回
60 |
61 | > 例子:[pf_array_rand_by_weight()](./pf_array_rand_by_weight.php)
62 |
63 | - pf_deep_in_array() 二维数组验证一个值是否存在
64 |
65 | > 例子:[pf_deep_in_array()](./pf_deep_in_array.php)
66 |
67 | - pf_rand_val() 随机返回数组元素
68 |
69 | > 例子:[pf_rand_val()](./pf_rand_val.php)
70 |
71 | - pf_rand_weighted() 按权重 随机返回数组的值
72 |
73 | > 例子:[pf_rand_weighted()](./pf_rand_weighted.php)
74 |
75 | - pf_array_shuffle() 随机打乱数组
76 |
77 | > 例子:[pf_array_shuffle()](./pf_array_shuffle.php)
78 |
79 | - pf_array_insert() 在数组中的给定位置插入元素
80 |
81 | > 例子:[pf_array_insert()](./pf_array_insert.php)
82 |
83 | - pf_array_diff_both() 返回两个数组中不同的元素
84 |
85 | > 例子:[pf_array_diff_both()](./pf_array_diff_both.php)
86 |
--------------------------------------------------------------------------------
/src/build/PFDateArr.php:
--------------------------------------------------------------------------------
1 | _/___.' >'"".
23 | * | | : `- \`.;`\ _ /`;.`/ - ` : | |
24 | * \ \ `-. \_ __\ /__ _/ .-` / /
25 | * ========`-.____`-.___\_____/___.-`____.-'========
26 | * `=---='
27 | * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
28 | * 佛祖保佑 永无BUG 永不修改
29 | *
30 | */
31 |
32 | namespace pf\arr\build;
33 |
34 |
35 | trait PFDateArr
36 | {
37 | /**
38 | * 生成一个日期数组
39 | * @param $from
40 | * @param $to
41 | * @param string $step
42 | * @param string $outputFormat
43 | * @return array
44 | */
45 | public static function pf_date_indexed($from, $to, $step = '+1 day', $outputFormat = 'Y-m-d') {
46 | $dates = array();
47 | $current = strtotime($from);
48 | $last = strtotime($to);
49 | while($current <= $last) {
50 | $dates[] = date($outputFormat, $current);
51 | $current = strtotime($step, $current);
52 | }
53 | return $dates;
54 | }
55 |
56 | /**
57 | * 产生一个关联数组
58 | * @param $from
59 | * @param $to
60 | * @param null $default
61 | * @param string $step
62 | * @param string $outputFormat
63 | * @return array
64 | */
65 | public static function pf_date_assoc($from, $to, $default = null, $step = '+1 day', $outputFormat = 'Y-m-d')
66 | {
67 | $dates = self::pf_date_indexed($from, $to, $step, $outputFormat);
68 | return array_fill_keys($dates, $default);
69 | }
70 | }
--------------------------------------------------------------------------------
/src/build/PFArrFormat.php:
--------------------------------------------------------------------------------
1 | 'format_json',
8 | 'xml'=>'format_xml',
9 | 'serialize'=>'format_serialize',
10 | 'obj' =>'format_obj',
11 | 'csv' =>'format_csv'
12 | );
13 |
14 | public function pf_encode($array,$type='json') {
15 | if(method_exists($this, $this->type_func[$type])) {
16 | return call_user_func(array($this,$this->type_func[$type]), $array);
17 | }
18 | else{
19 | throw new Exception(sprintf('The required method "'.$this->type_func[$type].'" does not exist for!', $this->type_func[$type], get_class($this)));
20 | }
21 | }
22 |
23 | private function format_json($array) {
24 | return json_encode($array);
25 | }
26 |
27 | private function format_xml($array) {
28 | if (ini_get('zend.ze1_compatibility_mode') == 1)
29 | {
30 | ini_set ('zend.ze1_compatibility_mode', 0);
31 | }
32 | return $this->toXml($array,$this->rootNodeName);
33 | }
34 |
35 | private function format_serialize($array) {
36 | $array = serialize($array);
37 | return $array;
38 | }
39 |
40 | private function toXml($data, $rootNodeName = 'root', $xml=null) {
41 | if ($xml == null)
42 | {
43 | $xml = simplexml_load_string("<$rootNodeName />");
44 | }
45 | foreach($data as $key => $value)
46 | {
47 | if (is_numeric($key))
48 | {
49 | $key = "unknownNode_". (string) $key;
50 | }
51 |
52 | if (is_array($value))
53 | {
54 | $node = $xml->addChild($key);
55 | $this->toXml($value, $rootNodeName, $node);
56 | }
57 | else
58 | {
59 | $value =htmlentities($value,ENT_QUOTES,'UTF-8');
60 | $xml->addChild($key,$value);
61 | }
62 |
63 | }
64 | return $xml->asXML();
65 | }
66 |
67 | public function format_csv($data)
68 | {
69 | if (is_array($data) and isset($data[0]))
70 | {
71 | $headings = array_keys($data[0]);
72 | }
73 | else
74 | {
75 | $headings = array_keys((array) $data);
76 | $data = array($data);
77 | }
78 | $output = implode(',', $headings) . "\r\n";
79 | foreach ($data as &$row)
80 | {
81 | $output .= '"' . implode('","', (array) $row) . "\"\r\n";
82 | }
83 | return $output;
84 | }
85 |
86 |
87 | private function format_obj($array) {
88 | $array = json_encode($array);
89 | $arr = json_decode($array,false);
90 | return $arr;
91 | }
92 | }
--------------------------------------------------------------------------------
/example/pf_arr_group_by.php:
--------------------------------------------------------------------------------
1 | 0,
8 | 'city' => '上海',
9 | 'object' => '公交',
10 | ],
11 | [
12 | 'state' => 1,
13 | 'city' => '广州',
14 | 'object' => '私家车',
15 | ],
16 | [
17 | 'state' => 0,
18 | 'city' => '山东',
19 | 'object' => '公交',
20 | ],
21 | [
22 | 'state' => 1,
23 | 'city' => '上海',
24 | 'object' => '私家车',
25 | ],
26 | [
27 | 'state' => 0,
28 | 'city' => '山东',
29 | 'object' => '毛驴',
30 | ],
31 | ];
32 | echo '';
33 | print_r(PFarr::pf_array_group_by($records, 'city'));
34 |
35 | /*
36 | * //返回结果
37 | Array
38 | (
39 | [上海] => Array
40 | (
41 | [0] => Array
42 | (
43 | [state] => 0
44 | [city] => 上海
45 | [object] => 公交
46 | )
47 |
48 | [1] => Array
49 | (
50 | [state] => 1
51 | [city] => 上海
52 | [object] => 私家车
53 | )
54 |
55 | )
56 |
57 | [广州] => Array
58 | (
59 | [0] => Array
60 | (
61 | [state] => 1
62 | [city] => 广州
63 | [object] => 私家车
64 | )
65 | )
66 | [山东] => Array
67 | (
68 | [0] => Array
69 | (
70 | [state] => 0
71 | [city] => 山东
72 | [object] => 公交
73 | )
74 | [1] => Array
75 | (
76 | [state] => 0
77 | [city] => 山东
78 | [object] => 毛驴
79 | )
80 | )
81 |
82 | )
83 | */
84 |
85 | print_r(PFarr::pf_array_group_by($records, 'city', 'state'));
86 |
87 | /* 返回
88 | Array
89 | (
90 | [上海] => Array
91 | (
92 | [0] => Array
93 | (
94 | [0] => Array
95 | (
96 | [state] => 0
97 | [city] => 上海
98 | [object] => 公交
99 | )
100 |
101 | )
102 |
103 | [1] => Array
104 | (
105 | [0] => Array
106 | (
107 | [state] => 1
108 | [city] => 上海
109 | [object] => 私家车
110 | )
111 |
112 | )
113 |
114 | )
115 |
116 | [广州] => Array
117 | (
118 | [1] => Array
119 | (
120 | [0] => Array
121 | (
122 | [state] => 1
123 | [city] => 广州
124 | [object] => 私家车
125 | )
126 |
127 | )
128 |
129 | )
130 |
131 | [山东] => Array
132 | (
133 | [0] => Array
134 | (
135 | [0] => Array
136 | (
137 | [state] => 0
138 | [city] => 山东
139 | [object] => 公交
140 | )
141 |
142 | [1] => Array
143 | (
144 | [state] => 0
145 | [city] => 山东
146 | [object] => 毛驴
147 | )
148 |
149 | )
150 |
151 | )
152 |
153 | )
154 | */
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # pfinal-array
2 |
3 | [](https://github.com/pfinalclub/pfinal-array)
4 | [](https://github.com/pfinalclub/pfinal-array)
5 | [](https://github.com/pfinalclub/pfinal-array)
6 | [](https://github.com/pfinalclub/pfinal-array)
7 |
8 | **Note:** ```PHP``` ```PHPArray``` ```Validator```
9 |
10 | 这是一个PHP数组操作增强组件,对 PHP 数组的常用操作进行封装
11 |
12 | 目前包括以下方法:
13 |
14 | | 函数名 | 函数描述 |
15 | | ---- | ---- |
16 | | pf_del_val() |删除数组中的某个值|
17 | | pf_key_exists() | 判断数组中是否有这个键|
18 | | pf_get() | 根据键名获取数组中的某个值,支持点语法|
19 | | pf_set() | 设置数组元素值支持点语法|
20 | | pf_arr_sort() | 数组排序|
21 | | pf_tree() | 二级数组树结构化(不递归)|
22 | | pf_get_tree() | 多级数组结构化(不递归)|
23 | | pf_array_unique() | 多维数组去重 |
24 | | pf_array_depth() | 检测数组的维度|
25 | | pf_encode() | 数据格式转换支持 数组转 'json','xml','csv','serialize'|
26 | | pf_array_flatten() | 将多维折叠数组变为一维|
27 | | pf_is_list() | 判断PHP数组是否索引数组|
28 | | pf_array_rand_by_weight() | 根据权重获取随机区间返回ID|
29 | | pf_rand_val() | 随机获取数组中的元素|
30 | | pf_rand_weighted() | 按权重 随机返回数组的值|
31 | | pf_array_shuffle() | 随机打乱数组(支持多维数组)|
32 | | pf_array_insert() | 在数组中的给定位置插入元素|
33 | | pf_array_diff_both() | 返回两个数组中不同的元素|
34 | | pf_array_group_by() | 按指定的键对数组依次分组|
35 | | pf_array_null() | 把数组中的null转换成空字符串|
36 | | pf_count_element() | 统计数组中元素出现的次数|
37 | | pf_map() | 重组数组|
38 | | pf_exists() | 判断数组中某个键有木有值|
39 | | pf_arr_group_by() | 按指定值给数组分组|
40 | | pf_arr_sort_by_key() | 按指定键给数组排序|
41 | | pf_arr_remove_empty() | 递归过滤多维数组中 空白字符,负值,false,null|
42 | | pf_date_indexed() | 生成一个日期数组|
43 | | pf_date_assoc() | 产生一个关联数组|
44 | | pf_array_where() | 使用给定闭包对数组进行过滤|
45 | | pf_array_first() | 获取数组的第一个元素|
46 | | pf_array_last() | 获取数组的最后一个元素|
47 |
48 | ## 安装
49 |
50 | 通过 Composer 安装:
51 |
52 | ```composer
53 | composer require nancheng/pfinal-array
54 | ```
55 | ---
56 |
57 | ## 使用
58 |
59 | ```php
60 |
61 | require './vendor/autoload.php';
62 | use pf\arr\PFarr;
63 | // 调用方法
64 | ```
65 |
66 | ## 例子
67 |
68 |
69 |
70 | *多维数组去重*
71 |
72 | ```php
73 | $arr = [1,54,'a',45,12,'c',1,1,12,[1,1,'a',['a','b','a']]];
74 | $arr = PFarr::pf_array_unique($arr);
75 | echo '';
76 | print_r($arr);
77 |
78 |
79 | // 结果
80 | Array
81 | (
82 | [0] => 1
83 | [1] => 54
84 | [2] => a
85 | [3] => 45
86 | [4] => 12
87 | [5] => c
88 | [9] => Array
89 | (
90 | [0] => 1
91 | [2] => a
92 | [3] => Array
93 | (
94 | [0] => a
95 | [1] => b
96 | )
97 |
98 | )
99 |
100 | )
101 | ```
102 |
103 | *获取指定列的数据*
104 |
105 | ```php
106 | $result = PFarr::pf_array_col($records, 'first_name', 'id');
107 | print_r($result);
108 | ```
109 |
110 | *按指定的键对数组依次分组*
111 |
112 | ```php
113 | $records = [
114 | [
115 | 'city' => '上海',
116 | 'age' => 18,
117 | 'name' => '马二'
118 | ],
119 | [
120 | 'city' => '上海',
121 | 'age' => 20,
122 | 'name' => '翠花'
123 | ]
124 | ];
125 |
126 | //按照 city 分组
127 | $arr = PFarr::pf_array_group_by($records,'city');
128 |
129 | //按照 city 分组 完成 之后 再按照 age 分组
130 |
131 | $arr1 = PFarr::pf_array_group_by($records,'city','age');
132 |
133 | ```
134 | *组词算法*
135 | ```php
136 | 1
162 | [b] => 1
163 | [c] => 1
164 | [d] => 1
165 | )
166 | */
167 |
168 | PFarr::dd(PFarr::pf_count_element($arr_two));
169 | /*
170 | 返回
171 | Array
172 | (
173 | [a] => 2
174 | [b] => 2
175 | [c] => 1
176 | [d] => 1
177 | )
178 |
179 | */
180 |
181 |
182 | ```
183 | *从多维数组或对象数组构建一个映射(键-值对)。*
184 |
185 | ```php
186 | '123', 'name' => 'aaa', 'class' => 'x'],
189 | ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
190 | ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
191 | ];
192 |
193 | PFarr::dd(PFarr::pf_map($array,'id','name'));
194 |
195 | /*
196 | 返回:
197 | Array
198 | (
199 | [123] => aaa
200 | [124] => bbb
201 | [345] => ccc
202 | )
203 | */
204 |
205 |
206 | PFarr::dd(PFarr::pf_map($array,'id','name','class'));
207 | /*
208 | 返回
209 | Array
210 | (
211 | [x] => Array
212 | (
213 | [123] => aaa
214 | [124] => bbb
215 | )
216 |
217 | [y] => Array
218 | (
219 | [345] => ccc
220 | )
221 |
222 | )
223 | */
224 |
225 | ```
226 | 查看更多例子:[更多](./example/README.md)
227 |
228 | ### 其他
229 |
230 | 继续完善
231 |
--------------------------------------------------------------------------------
/src/build/PFArrCheck.php:
--------------------------------------------------------------------------------
1 | [],
117 | 'lastKey' => '',
118 | 'prevEl' => &$array,
119 | 'currEl' => &$array,
120 | 'isExists' => null,
121 | 'cntEBrackets' => 0,
122 | 'isString' => false,
123 | 'completed' => false,
124 | 'first' => true,
125 | 'append' => false,
126 | 'value' => null
127 | ];
128 | $parseInfo['isBroken'] = (bool)preg_replace_callback(array('/(?J:\[([\'"])(?.*?)\1\]|(?\]?[^\[]+)|\[(?(?:[^\[\]]+|(?R))*)\])/'),
129 | function ($m) use (&$parseInfo, &$array) {
130 | if ($m[0] == '[]') {
131 | $parseInfo['isExists'] = false;
132 | $parseInfo['cntEBrackets']++;
133 | $parseInfo['append'] = $parseInfo['cntEBrackets'] == 1;
134 | return '';
135 | }
136 | $parseInfo['append'] = false;
137 | $parseInfo['keys'][] = $m['el'];
138 | if ($parseInfo['isExists'] !== false) {
139 | if (!is_array($parseInfo['currEl'])) {
140 | $parseInfo['isExists'] = false;
141 | $parseInfo['lastKey'] = $m['el'];
142 | return '';
143 | }
144 | if (($parseInfo['isExists'] = array_key_exists((string)$m['el'],
145 | $parseInfo['currEl']) && is_array($parseInfo['currEl']))
146 | ) {
147 | if (!$parseInfo['first']) {
148 | $parseInfo['prevEl'] = &$parseInfo['currEl'];
149 | }
150 | $parseInfo['currEl'] = &$parseInfo['currEl'][$m['el']];
151 | $parseInfo['lastKey'] = $m['el'];
152 | $parseInfo['first'] = false;
153 | }
154 | }
155 | return '';
156 | }, $key);
157 | if ($parseInfo['isExists'] === false && is_array($parseInfo['prevEl']) && is_string($parseInfo['currEl'])) {
158 | $parseInfo['isString'] = true;
159 | if ($mode == 'get' && isset($parseInfo['currEl'][$parseInfo['lastKey']])) {
160 | $parseInfo['completed'] = true;
161 | $parseInfo['value'] = $parseInfo['currEl'][$parseInfo['lastKey']];
162 | }
163 | }
164 | if ($mode == 'get' && $parseInfo['isExists']) {
165 | $parseInfo['completed'] = true;
166 | $parseInfo['value'] = $parseInfo['prevEl'][$parseInfo['lastKey']];
167 | }
168 | if ($mode == 'delete' && $parseInfo['isExists']) {
169 | unset($parseInfo['prevEl'][$parseInfo['lastKey']]);
170 | $parseInfo['completed'] = true;
171 | }
172 | if ($mode == 'save') {
173 | if ($parseInfo['append']) {
174 | if ($parseInfo['cntEBrackets'] == 1) {
175 | $parseInfo['completed'] = true;
176 | }
177 | } else {
178 | if ($parseInfo['cntEBrackets'] == 0) {
179 | $parseInfo['completed'] = true;
180 | }
181 | }
182 | }
183 | if ($parseInfo['isBroken']) {
184 | $parseInfo['completed'] = false;
185 | }
186 | return $parseInfo;
187 | }
188 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/src/build/Base.php:
--------------------------------------------------------------------------------
1 | $v) {
22 | if (!in_array($v, $values)) {
23 | $news[$key] = $v;
24 | }
25 | }
26 | return $news;
27 | }
28 |
29 | /**
30 | * 根据键名获取值 支持点语法
31 | * @param array $data
32 | * @param $key
33 | * @param null $value
34 | * @return array|mixed|null
35 | */
36 | public function pf_get(array $data, $key, $value = null)
37 | {
38 | $exp = explode('.', $key);
39 | foreach ((array)$exp as $d) {
40 | if (isset($data[$d])) {
41 | $data = $data[$d];
42 | } else {
43 | return $value;
44 | }
45 | }
46 | return $data;
47 | }
48 |
49 | /**
50 | * 设置数组元素值支持点语法
51 | * @param array $data
52 | * @param $key
53 | * @param $value
54 | * @return array
55 | */
56 | public function pf_set(array $data, $key, $value)
57 | {
58 | $tmp =& $data;
59 | foreach (explode('.', $key) as $d) {
60 | if (!isset($tmp[$d])) {
61 | $tmp[$d] = [];
62 | }
63 | $tmp = &$tmp[$d];
64 | }
65 | $tmp = $value;
66 | return $data;
67 | }
68 |
69 | /**
70 | * 不区分大小写 检测数据数据键名
71 | * @param $arr
72 | * @param $key
73 | * @return bool
74 | */
75 | public function pf_key_exists($arr, $key)
76 | {
77 | if (!is_array($arr)) return false;
78 | if (array_key_exists(strtolower($key), $arr)) {
79 | return true;
80 | } else {
81 | foreach ($arr as $value) {
82 | if (is_array($value)) {
83 | return $this->pf_key_exists($value, $key);
84 | }
85 | }
86 | }
87 | }
88 |
89 | /**
90 | * 过滤数组
91 | * @param array $data
92 | * @param array $keys
93 | * @param int $type
94 | * @return array
95 | */
96 | public function pf_filter_keys(array $data, array $keys, $type = 1)
97 | {
98 | $tmp = $data;
99 | foreach ($data as $k => $v) {
100 | if ($type == 1) {
101 | //存在时过滤
102 | if (in_array($k, $keys)) {
103 | unset($tmp[$k]);
104 | }
105 | } else {
106 | //不在时过滤
107 | if (!in_array($k, $keys)) {
108 | unset($tmp[$k]);
109 | }
110 | }
111 | }
112 | return $tmp;
113 | }
114 |
115 | /**
116 | * 多维数组排序
117 | * @param $arr
118 | * @return mixed
119 | */
120 | public function pf_arr_sort($arr)
121 | {
122 | $len = count($arr);
123 | for ($i = 1; $i < $len; $i ++) {
124 | for ($k = 0; $k < $len - $i; $k ++) {
125 | if (is_array($arr[$k + 1])) {
126 | $arr[$k + 1] = $this->pf_arr_sort($arr[$k + 1]);
127 | } else {
128 | if ($arr[$k] > $arr[$k + 1]) {
129 | $tmp = $arr[$k + 1];
130 | $arr[$k + 1] = $arr[$k];
131 | $arr[$k] = $tmp;
132 | }
133 | }
134 | }
135 | }
136 | return $arr;
137 | }
138 |
139 | /**
140 | * 二级获取树形结构
141 | * @param $list
142 | * @param int $parent_id
143 | * @param string $field
144 | * @param string $field_key
145 | * @return array
146 | */
147 | public function pf_tree($list, $parent_id = 0, $field = 'parent_id', $field_key = 'id')
148 | {
149 | $arr = [];
150 | $tree = [];
151 | foreach ($list as $value) {
152 | $arr[$value[$field]][] = $value;
153 | }
154 |
155 | foreach ($arr[$parent_id] as $key => $val) {
156 | $tree[$key][] = $val;
157 | if (isset($arr[$val[$field_key]]) && count($arr[$val[$field_key]]) > 0) {
158 | foreach ($arr[$val[$field_key]] as $v) {
159 | $tree[$key]['son'][] = $v;
160 | }
161 | }
162 | }
163 | return $tree;
164 | }
165 |
166 | /**
167 | * 多级获取树形结构
168 | * @param $list
169 | * @param int $parent_id
170 | * @param string $field
171 | * @param string $field_key
172 | * @return array
173 | */
174 | public function pf_get_tree($list, $parent_id = 0, $field = 'parent_id', $field_key = 'id')
175 | {
176 | $tree = [];
177 | if (!empty($list)) {
178 | //先修改为以id为下标的列表
179 |
180 | $newList = [];
181 |
182 | foreach ($list as $k => $v) {
183 | $newList[$v[$field_key]] = $v;
184 | }
185 | //然后开始组装成特殊格式
186 | foreach ($newList as $value) {
187 |
188 | if ($parent_id == $value[$field]) {//先取出顶级
189 | $tree[] = &$newList[$value[$field_key]];
190 | } elseif (isset($newList[$value[$field]])) {
191 | //再判定非顶级的pid是否存在,如果存在,则再pid所在的数组下面加入一个字段items,来将本身存进去
192 | $newList[$value[$field]]['items'][] = &$newList[$value[$field_key]];
193 |
194 | }
195 | }
196 | }
197 | return $tree;
198 | }
199 |
200 | /**
201 | * 数组去重
202 | * @param $arr
203 | * @return array
204 | */
205 | public function pf_array_unique($arr)
206 | {
207 | $dime = $this->pf_array_depth($arr);
208 | if ($dime <= 1) {
209 | $data = array_unique($arr);
210 | } else {
211 | $temp = [];
212 | $new_data = [];
213 | foreach ($arr as $key => $v) {
214 | if (is_array($v)) {
215 | $new_data = $this->pf_array_unique($v);
216 | } else {
217 | $temp[$key] = $v;
218 | }
219 | }
220 | $data = array_unique($temp);
221 | array_push($data, $new_data);
222 | }
223 | return $data;
224 | }
225 |
226 | /**
227 | * 检测数组的维度
228 | * @param $array
229 | * @return int
230 | */
231 | public function pf_array_depth($array)
232 | {
233 | if (!is_array($array)) return 0;
234 | $max_depth = 1;
235 | foreach ($array as $value) {
236 | if (is_array($value)) {
237 | $depth = $this->pf_array_depth($value) + 1;
238 |
239 | if ($depth > $max_depth) {
240 | $max_depth = $depth;
241 | }
242 | }
243 | }
244 | return $max_depth;
245 | }
246 |
247 | /**
248 | * 数组中指定的一列
249 | * @param $array
250 | * @param $columnKey
251 | * @param null $indexKey
252 | * @return array
253 | */
254 | public function pf_array_col($array, $columnKey, $indexKey = null)
255 | {
256 | $result = array();
257 | if (!empty($array)) {
258 | if (!function_exists('array_column')) {
259 | foreach ($array as $val) {
260 | if (!is_array($val)) {
261 | continue;
262 | } elseif (is_null($indexKey) && array_key_exists($columnKey, $val)) {
263 | $result[] = $val[$columnKey];
264 | } elseif (array_key_exists($indexKey, $val)) {
265 | if (is_null($columnKey)) {
266 | $result[$val[$indexKey]] = $val;
267 | } elseif (array_key_exists($columnKey, $val)) {
268 | $result[$val[$indexKey]] = $val[$columnKey];
269 | }
270 | }
271 | }
272 | } else {
273 | $result = array_column($array, $columnKey, $indexKey);
274 | }
275 | }
276 | return $result;
277 | }
278 |
279 | /**
280 | * 对象转换成数组
281 | * @param $obj
282 | * @return array
283 | */
284 | public function pf_obj_arr($obj)
285 | {
286 | $arr = is_object($obj) ? get_object_vars($obj) : $obj;
287 | if (is_array($arr)) {
288 | return array_map(array(
289 | __CLASS__,
290 | __FUNCTION__
291 | ), $arr);
292 | } else {
293 | return $arr;
294 | }
295 | }
296 |
297 | /**
298 | * 将多维折叠数组变为一维
299 | *
300 | * @param array $values 多维数组
301 | * @param bool $drop_empty 去掉为空的值
302 | * @return array
303 | */
304 | public function pf_array_flatten(array $values, $drop_empty = false)
305 | {
306 | $result = [];
307 | array_walk_recursive($values, function ($value)
308 | use (&$result, $drop_empty) {
309 | if (!$drop_empty || !empty($value)) {
310 | $result[] = $value;
311 | }
312 | });
313 | return $result;
314 | }
315 |
316 |
317 | /**
318 | * 根据权重获取随机区间返回ID
319 | * @param array $array 格式为 array(array('id'=>'','value'=>''),array('id'=>'','value'=>'')) //id为标识,value为权重
320 | * @return int|string
321 | */
322 | public function pf_array_rand_by_weight($array)
323 | {
324 | if (!empty($array)) {
325 | //区间最大值
326 | $sum = 0;
327 | //区间数组
328 | $interval = array();
329 | //制造区间
330 | foreach ($array as $value) {
331 |
332 | $interval[$value['id']]['min'] = $sum + 1;
333 | $interval[$value['id']]['max'] = $sum + $value['value'];
334 | $sum += $value['value'];
335 | }
336 | //在区间内随机一个数
337 | $result = rand(1, $sum);
338 | //获取结果属于哪个区间, 返回其ID
339 |
340 | foreach ($interval as $id => $v) {
341 |
342 | while ($result >= $v['min'] && $result <= $v['max']) {
343 | return $id;
344 | }
345 | }
346 | }
347 | return 0;
348 | }
349 |
350 | /**
351 | * 二维数组验证一个值是否存在
352 | * @param $value
353 | * @param $array
354 | * @return bool
355 | */
356 | public function pf_deep_in_array($array, $value)
357 | {
358 | foreach ($array as $item) {
359 | if (!is_array($item)) {
360 | if ($item == $value) {
361 | return true;
362 | } else {
363 | continue;
364 | }
365 | }
366 |
367 | if (in_array($value, $item)) {
368 | return true;
369 | } else if ($this->pf_deep_in_array($item, $value)) {
370 | return true;
371 | }
372 | }
373 | return false;
374 | }
375 |
376 |
377 | /**
378 | * 随机返回 数组 的值
379 | * @param $array
380 | * @param int $len
381 | * @return array|bool|mixed
382 | */
383 | public function pf_rand_val($array, $len = 1)
384 | {
385 | if (!is_array($array)) {
386 | return false;
387 | }
388 | $keys = array_rand($array, $len);
389 | if ($len === 1) {
390 | return $array[$keys];
391 | }
392 | return array_intersect_key($array, array_flip($keys));
393 | }
394 |
395 |
396 | /**
397 | * 按权重 随机返回数组的值
398 | * Example:$arr = [['dd',1],['ff',2],['cc',3],['ee',4]]; 出现 ee的次数相对于其他的次数要多一点
399 | * @param array $array
400 | * @return array|bool|mixed
401 | */
402 | public function pf_rand_weighted(array $array)
403 | {
404 | if (!is_array($array)) {
405 | return false;
406 | }
407 |
408 | $options = [];
409 | foreach ($array as $weight) {
410 | if (!is_array($weight)) {
411 | return false;
412 | }
413 | for ($i = 0; $i < $weight[1]; ++ $i) {
414 | $options[] = $weight[0];
415 | }
416 | }
417 | return $this->pf_rand_val($options);
418 | }
419 |
420 | /**
421 | * 随机打乱数组
422 | * @param $array
423 | * @param bool $statue true or false
424 | * @return bool
425 | */
426 | public function pf_array_shuffle($array, $statue = false)
427 | {
428 | $keys = array_keys($array);
429 | shuffle($keys);
430 | $new = [];
431 | foreach ($keys as $key) {
432 | if (is_array($array[$key] && $statue)) {
433 | $new[$key] = $this->pf_array_shuffle($array[$key], 1);
434 | }
435 | $new[$key] = $array[$key];
436 | }
437 | return $new;
438 | }
439 |
440 | /**
441 | * 在数组中的给定位置插入元素
442 | * @param $array
443 | * @param $insert
444 | * @param int $position
445 | * @return array
446 | */
447 | public function pf_array_insert($array, $insert, $position = 0)
448 | {
449 | if (!is_array($insert)) {
450 | $insert = [$insert];
451 | }
452 |
453 | if ($position == 0) {
454 | $array = array_merge($insert, $array);
455 | } else {
456 | if ($position >= (count($array) - 1)) {
457 | $array = array_merge($array, $insert);
458 | } else {
459 | $head = array_slice($array, 0, $position);
460 | $tail = array_slice($array, $position);
461 | $array = array_merge($head, $insert, $tail);
462 | }
463 | }
464 | return $array;
465 | }
466 |
467 | /**
468 | * 返回两个数组中不同的元素
469 | * @param $array
470 | * @param $array1
471 | * @return array
472 | */
473 | public function pf_array_diff_both($array, $array1)
474 | {
475 | return array_merge(array_diff($array, $array1), array_diff($array1, $array));
476 | }
477 |
478 | /**
479 | * 按指定的键对数组依次分组
480 | * @param array $arr
481 | * @param $key
482 | * @return array|bool
483 | */
484 | public function pf_array_group_by(array $arr, $key)
485 | {
486 | if (!is_string($key) && !is_int($key)) {
487 | return false;
488 | }
489 | $is_function = !is_string($key) && is_callable($key);
490 | $grouped = [];
491 | foreach ($arr as $value) {
492 | $groupKey = null;
493 | if ($is_function) {
494 | $groupKey = $key($value);
495 | } else if (is_object($value)) {
496 | $groupKey = $value->{$key};
497 | } else {
498 | if (!isset($value[$key])) {
499 | return false;
500 | }
501 | $groupKey = $value[$key];
502 | }
503 | $grouped[$groupKey][] = $value;
504 | }
505 | if (func_num_args() > 2) {
506 | $args = func_get_args();
507 | foreach ($grouped as $groupKey => $value) {
508 | $params = array_merge([$value], array_slice($args, 2, func_num_args()));
509 | $grouped[$groupKey] = call_user_func_array([$this, 'pf_array_group_by'], $params);
510 | }
511 | }
512 | return $grouped;
513 | }
514 |
515 | /**
516 | * 把数组中的null 转换成 空字符串
517 | * @param $arr
518 | * @return array|string
519 | */
520 | public function pf_array_null($arr)
521 | {
522 |
523 | if ($arr !== null) {
524 | if (is_array($arr)) {
525 | if (!empty($arr)) {
526 | foreach ($arr as $key => $value) {
527 | if ($value === null) {
528 | $arr[$key] = '';
529 | } else {
530 | $arr[$key] = $this->pf_array_null($value); //递归再去执行
531 | }
532 | }
533 | } else {
534 | $arr = '';
535 | }
536 | } else {
537 | if ($arr === null) {
538 | $arr = '';
539 | }
540 | }
541 | } else {
542 | $arr = '';
543 | }
544 | return $arr;
545 | }
546 |
547 | /**
548 | * 统计数组元素出现的次数
549 | * @return array|bool
550 | */
551 | public function pf_count_element()
552 | {
553 | $data = func_get_args();
554 | $num = func_num_args();
555 | $result = array();
556 | if ($num > 0) {
557 | for ($i = 0; $i < $num; $i ++) {
558 | foreach ($data[$i] as $v) {
559 | if (isset($result[$v])) {
560 | $result[$v] ++;
561 | } else {
562 | $result[$v] = 1;
563 | }
564 | }
565 | }
566 | return $result;
567 | }
568 | return false;
569 | }
570 |
571 | /**
572 | * 重组数组
573 | * @param $array
574 | * @param $from
575 | * @param $to
576 | * @param null $group
577 | * @return array
578 | */
579 | public function pf_map($array, $from, $to, $group = null)
580 | {
581 | if (!is_array($array)) {
582 | return array();
583 | }
584 | $result = [];
585 | foreach ($array as $element) {
586 | if (!array_key_exists($from, $element) or !array_key_exists($to, $element)) {
587 | continue;
588 | }
589 | $key = $element[$from];
590 | $value = $element[$to];
591 | if ($group !== null) {
592 | if (!array_key_exists($group, $element)) {
593 | continue;
594 | }
595 | $result[$element[$group]][$key] = $value;
596 | } else {
597 | $result[$key] = $value;
598 | }
599 | }
600 |
601 | return $result;
602 | }
603 |
604 | /**
605 | * 按指定值去给数组排序
606 | * @param array $arr
607 | * @param $key
608 | * @return array
609 | */
610 | public function pf_arr_group_by(array $arr, $key)
611 | {
612 | if (!is_string($key) && !is_int($key) && !is_float($key) && !is_callable($key)) {
613 | trigger_error('array_group_by():键应该是一个字符串、一个整数、一个浮点数或一个函数', E_USER_ERROR);
614 | }
615 | $isFunction = !is_string($key) && is_callable($key);
616 | // Load the new array, splitting by the target key
617 | $grouped = [];
618 | foreach ($arr as $value) {
619 | $groupKey = null;
620 | if ($isFunction) {
621 | $groupKey = $key($value);
622 | } else if (is_object($value)) {
623 | $groupKey = $value->{$key};
624 | } else {
625 | $groupKey = $value[$key];
626 | }
627 | $grouped[$groupKey][] = $value;
628 | }
629 |
630 | if (func_num_args() > 2) {
631 | $args = func_get_args();
632 | foreach ($grouped as $groupKey => $value) {
633 | $params = array_merge([$value], array_slice($args, 2, func_num_args()));
634 | $grouped[$groupKey] = call_user_func_array(array($this, 'self::pf_arr_group_by'), $params);
635 | }
636 | }
637 | return $grouped;
638 | }
639 |
640 | /**
641 | * 按指定键给数组排序
642 | * @param $arr
643 | * @param $key
644 | * @param string $orderby
645 | * @return array|bool
646 | */
647 | public function pf_arr_sort_by_key($arr, $key, $orderby = 'asc')
648 | {
649 | if (count($arr) < 0) return false;
650 | $keys_value = [];
651 | $new_array = [];
652 | foreach ($arr as $k => $v) {
653 | $keys_value[$k] = $v[$key];
654 | }
655 | if ($orderby == 'asc') {
656 | asort($keys_value);
657 | } else {
658 | arsort($keys_value);
659 | }
660 | reset($keys_value);
661 | foreach ($keys_value as $k => $v) {
662 | $new_array[] = $arr[$k];
663 | }
664 | return $new_array;
665 | }
666 |
667 | /**
668 | * 递归过滤多维数组中 空白字符,负值,false,null
669 | * @param $arr
670 | * @param bool $trim
671 | * @param bool $unsetEmptyArr
672 | * @return array
673 | */
674 |
675 | public function pf_arr_remove_empty(&$arr, $trim = true, $unsetEmptyArr = false)
676 | {
677 | foreach ($arr as $key => $value) {
678 | if (is_array($value)) {
679 | $this->pf_arr_remove_empty($arr[$key]);
680 | } else {
681 | $value = trim($value);
682 | if ($value == '') {
683 | unset($arr[$key]);
684 | } elseif ($trim) {
685 | $arr[$key] = $value;
686 | }
687 | }
688 | }
689 | if (is_bool($unsetEmptyArr) && $unsetEmptyArr) {
690 | $arr = array_filter($arr);
691 | }
692 | return $arr;
693 | }
694 |
695 | /**
696 | * 使用给定闭包对数组进行过滤
697 | * @param $array
698 | * @param callable $callback
699 | * @return array
700 | */
701 | public function pf_array_where($array, callable $callback)
702 | {
703 | return array_filter($array, $callback, ARRAY_FILTER_USE_BOTH);
704 | }
705 |
706 | /**
707 | * 获取数组第一个元素
708 | * @param $array
709 | * @param callable|null $callback
710 | * @param null $default
711 | * @return mixed
712 | */
713 | public function pf_array_first($array, callable $callback = null, $default = null)
714 | {
715 | if (is_null($callback)) {
716 | if (empty($array)) {
717 | return value($default);
718 | }
719 |
720 | foreach ($array as $item) {
721 | return $item;
722 | }
723 | }
724 | foreach ($array as $key => $value) {
725 | if (call_user_func($callback, $value, $key)) {
726 | return $value;
727 | }
728 | }
729 | return value($default);
730 | }
731 |
732 | /**
733 | * 获取数组最后一个元素
734 | * @param $array
735 | * @param callable|null $callback
736 | * @param null $default
737 | * @return mixed
738 | */
739 | public function pf_array_last($array, callable $callback = null, $default = null)
740 | {
741 | if (is_null($callback)) {
742 | return empty($array) ? value($default) : end($array);
743 | }
744 |
745 | return self::pf_array_first(array_reverse($array, true), $callback, $default);
746 | }
747 |
748 | /**
749 | * 结构化打印数组
750 | * @param $arr
751 | * @param int $type
752 | */
753 | public function dd($arr, $type = 1)
754 | {
755 | echo '';
756 | if ($type == 1) {
757 | print_r($arr);
758 | } else {
759 | var_dump($arr);
760 | exit;
761 | }
762 | echo '';
763 | }
764 |
765 | }
766 |
--------------------------------------------------------------------------------