1 回答

TA貢獻2016條經驗 獲得超9個贊
1. php中增加數組元素的方法:
(1)通過賦值增加數組元素 :$states[‘name’]=’Tom’;
(2)int array_push(array target_array,mixed variable [,mixed variable…]) 函數將variable增加到target_array的末尾,成功時返回true,否則返回false,其中variable可以是多個;
(3)int array_unshift(array target_array,mixed variable [,mixed variable…]) 函數將variable增加到target_array的數組頭,成功時返回true,否則返回false,其中variable可以是多個。所有已有的數值鍵都會相應地修改,而關聯鍵不受影響;
(4)array array_pad(array target_array,integer length,mixed pad_value) 將target_array 的大小增加到length指定的長度。
具體方法:
1.使用array_merge方法實現類似array_unshift在開頭添加元素的功能
代碼如下:
<?php
$queue = array('a', 'B');
$queue = array_merge(array('front' => 'hello'), $queue);
/*
Array
(
[front] => hello
[0] => a
[1] => b
)
*/
?>
2.+操作符
代碼如下:
<?php
$queue = array('a', 'B');
$queue = array('front' => 'Hello') + $queue;
?>
輸出結果與使用array_merge方法一樣。
3.在元素結尾添加關聯數組元素
代碼如下:
<?php
$queue = array('a', 'B');
$queue['front'] = 'hello';
/*
輸出
Array
(
[0] => a
[1] => b
[front] => hello
)
*/
?>
- 1 回答
- 0 關注
- 1496 瀏覽
添加回答
舉報