商讯信箱
用户名: @
密  码:   注册|忘记密码
登录
个人用户经销商
您的位置:首页 > 技术频道 > 正文

PHP 开发经典教程 (Part 4):数组

推进和拉出 

    你也可以使用array_push()函数在现有的数组末位增加元素:

<?php // define an array $pasta = array('spaghetti', 'penne', 'macaroni'); // add an element to the end array_push($pasta, 'tagliatelle'); print_r($pasta); ?>


     同时,你可以使用名字非常有趣的array_pop()函数从数组末端移除元素。

<?php // define an array $pasta = array('spaghetti', 'penne', 'macaroni'); // remove an element from the end array_pop($pasta); print_r($pasta); ?>

 

     如果你需要从数组顶部取元素,那么你可以使用array_shift()函数:

<?php // define an array $pasta = array('spaghetti', 'penne', 'macaroni'); // take an element off the top array_shift($pasta); print_r($pasta); ?>

 

     且array_unshift()函数负责增加元素到数组的起始端。

<?php // define an array $pasta = array('spaghetti', 'penne', 'macaroni'); // add an element to the beginning array_unshift($pasta, 'tagliatelle'); print_r($pasta); ?>

 

    array_push()和array_unshift()函数对与其等相关联的数组并不起作用;为了对该等数组添加元素,最好采用$arr[$key] = $value符号为数组增加新值。 

    explode()函数根据用户指定的分隔符将字符串分解为更小的单元,然后将分解得到的单元以数组的形式返回。

<?php // define CSV string $str = 'red, blue, green, yellow'; // split into individual words $colors = explode(', ', $str); print_r($colors); ?>

 

    为了执行和上面相反的过程,你可以使用implode()函数,该函数通过使用用户定义的分隔符将数组中的所有元素连接在一起而创建一个字符串。将上述例子颠倒过来,我们可以得到下面的代码:

<?php // define array $colors = array ('red', 'blue', 'green', 'yellow'); // join into single string with 'and' // returns 'red and blue and green and yellow' $str = implode(' and ', $colors); print $str; ?>

 

    最后,下面的两个例子展示了如何使用sort()和rsort()函数分别以升序和降序的方式对数组按字母(或数值)顺序来进行排序:

<?php // define an array $pasta = array('spaghetti', 'penne', 'macaroni'); // returns the array sorted alphabetically sort($pasta); print_r($pasta); print "<br />"; // returns the array sorted alphabetically in reverse rsort($pasta); print_r($pasta); ?>
1 2 3 4 5
【内容导航】
第1页: 一个大的错误 第2页: array()函数
第3页: 推进和拉出 第4页: 循环
第5页: 数组循环
©版权所有。未经许可,不得转载。
[责任编辑:赵建凯]
[an error occurred while processing this directive]