PHP数组的四个TIPS

WBOY
Release: 2016-06-13 11:00:32
Original
1064 people have browsed it

PHP数组的4个TIPS

最近工作中小结了对数组的一些TIPS
1) SORT
 
$website=array(“ labnol”,”sml”,”techiemania”,”softwarebuzzer”,”techperk”);

sort($website);

//sort alphabetically by value

print_r($website);

?>
SORT为对数组排序,输出为:
Array ( [0] => “labnol” [1] => ”sml” [2] => ”softwarebuzzer” [3] => ”techiemania” [4] => ”techperk” )

它的变体asort:
$my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse");

asort($my_array);
print_r($my_array);
?>
按值输出排序:
$my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse");

asort($my_array);
print_r($my_array);
?>

ksort:
ksort() 函数按照键名对数组排序,为数组值保留原来的键。

可选的第二个参数包含附加的排序标志。

若成功,则返回 TRUE,否则返回 FALSE。

$my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse");
ksort($my_array);
print_r($my_array);
?>
输出:

Array
(
[a] => Dog
[b] => Cat
[c] => Horse
)

2)Array_reverse(): 颠倒数组
 
$websites=array("devlup","techiemania","shoutmeloud","labnol");

print_r(array_reverse($websites));

?>
输出:
(“labnol”,”shoutmeloud”,”techiemania”,”devlup”)

3) explode和implode这两个就不多说了,很简单传统

4)array_slice()
函数在数组中根据条件取出一段值,并返回。

$a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird");
print_r(array_slice($a,1,2));
?>
array 必需。规定输入的数组。
offset 必需。数值。规定取出元素的开始位置。

如果是正数,则从前往后开始取,如果是负值,从后向前取 offset 绝对值。

length 可选。数值。规定被返回数组的长度。

如果是负数,则从后向前,选取该值绝对值数目的元素。如果未设置该值,则返回所有元素。

preserve 可选。可能的值:

true - 保留键
false - 默认 - 重置键

输出:

Array ( [0] => Cat [1] => Horse )

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!