0%

PHP Laravel 系列 - (4) 常見函式

1. array_column

依照指定欄位名稱(key)取出陣列

1
2
3
4
5
6
7
$records =[
['id' => 1, 'first_name' => 'kite'],
['id' => 2, 'first_name' => 'snow'],
['id' => 3, 'first_name' => 'bubu'],
];

print_r(array_column($records,'first_name'));

2. array_keys

回傳指定陣列的key

1
2
3
4
5
6
7
8
9
10
11
12
13
$records =[
['id' => 1, 'first_name' => 'kite'],
['id' => 2, 'first_name' => 'snow'],
['id' => 3, 'first_name' => 'bubu'],
];
print_r(array_keys($records[0]));
/*
Array
(
[0] => id
[1] => first_name
)
*/

3. array_values

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$records =[
['id' => 1, 'first_name' => 'kite'],
['id' => 2, 'first_name' => 'snow'],
['id' => 3, 'first_name' => 'bubu'],
];
print_r(array_values($records[0]));
/*
Array
(
[0] => 1
[1] => kite
)
*/
print_r(array_values($records));
/*
Array
(
[0] => 0
[1] => 1
[2] => 2
)
*/

4. array_map

1
2
3
4
5
6
7
8
9
10
11
12
$newRecords = array_map(function($record){
return $record['id'] = $record['id'] * 5;
},$records);
print_r($newRecords);
/*
Array
(
[0] => 5
[1] => 10
[2] => 15
)
*/

5. array_filter

1
2
3
4
5
6
7
8
$newRecords = array_filter(
$records,
function($record){
return $record['id'] >=2;
}
);

print_r($newRecords);

6. array_push

1
2
$num = [1,2,3,4];
array_push($nums,8);

7. array_pop

1
2
$num = [1,2,3,4];
array_pop($num);

8. array_merge

1
2
3
4
5
6
7
8
9
10
11
12
13
$person = ['id' => 5, 'name' => 'kite'];
$person = array_merge(
$person,
['name' => 'bubu', 'age' => 10]
);
/*
Array
(
[id] => 5
[name] => bubu
[age] => 10
)
*/

9. asort

value排序

1
2
3
4
5
6
7
8
9
10
11
12
$arr = ['d' =>'bubu' ,'c' => 'snow','b'=> 'kite' , 'a' =>'apple'];
sort($arr);
print_r($arr);
/*
Array
(
[0] => apple
[1] => bubu
[2] => kite
[3] => snow
)
*/

10. ksort

key排序

1
2
3
4
5
6
7
8
9
10
11
12
$arr = ['d' =>'bubu' ,'c' => 'snow','b'=> 'kite' , 'a' =>'apple'];
ksort($arr);
print_r($arr);
/*
Array
(
[0] => apple
[1] => bubu
[2] => kite
[3] => snow
)
*/
1
2
3
$people = ['john','tim','tim','kite'];
echo(array_search('kite',$people));
//3

12. array_unique

1
2
3
4
5
6
7
8
9
10
$people = ['john','tim','tim','kite'];
print_r(array_unique($people));
/*
Array
(
[0] => john
[1] => tim
[3] => kite
)
*/

13. array_sum

1
2
$nums = [1,2,3,4,5,6,7,8,9,10];
print_r(array_sum($nums));

14. count

1
2
$nums = [1,2,3,4,5,6,7,8,9,10];
echo(count($nums));