[精讚] [會員登入]
5383

[PHP] 陣列新增資料及整理

在php陣列加入項目和重新整理陣列的方法

分享此文連結 //n.sfs.tw/12800

分享連結 [PHP] 陣列新增資料及整理@新精讚
(文章歡迎轉載,務必尊重版權註明連結來源)
2019-10-25 11:19:55 最後編修
2018-10-12 01:17:58 By 張○○
 

自動目錄

PHP的陣列加項目很簡單,直接給定即可,不必宣告

$arr['one'] = "apple";

$arr[2] = "pineapple";

 

使用array_push函數

 

直接使用 array_push():

 

$arr =array("red","yellow","orange");
array_push($arr, "green", "blue", "black");
print_r($arr);
//Array ( [0] => red [1] => yellow [2] => orange [3] => green [4] => blue [5] => black )

另一個範例,不管中間有少了索引1的項目,還是會把項目加在後面

$arr =array(0=>"red",3=>"yellow",2=>"orange");  //Lack of index 1
array_push($arr, "green", "blue", "black");
print_r($arr);
//Array ( [0] => red [3] => yellow [2] => orange [4] => green [5] => blue [6] => black )

使用array_push 一次可加多個項目。

 

使用空白中刮號 []

中刮號的加項目法也很方便

$arr =array(0=>"red",5=>"orange");
$arr[]= "green";
$arr[]= "blue";
$arr[]= "black";
print_r($arr);
// Array ( [0] => red [5] => orange [6] => green [7] => blue [8] => black )

 

整理陣列索引

重新把索引號整理過

上面的例子如果使用 array_values 可以把陣列的索引值重新整理

$arr=array_values($arr);
print_r($arr);
// Array ( [0] => red [1] => orange [2] => green [3] => blue [4] => black )

做個簡單的筆記

 


原文 2010-11-02

END

你可能感興趣的文章

[PHP] 好用的php常數 介紹PHP中 __DIR__, __FILE__, __FUNCTION__, __CLASS__, __METHOD__, __LINE__, __NAMESPACE__等常數

[CodeIgniter 3] 修改或插入資料時遇到函數的處理 CI3 中要新增或修改的資料中如果有 now()這類的函數,要怎麼處理?

[CodeIgniter 3] 取得controller和method的方法 CodeIgniter 3 取得controller和method的方法

[PHP+ci4] codeignitor4 Cache 及 Session 使用 memcached php 的framework codeignitor4 中的cache和session使用memcached

[CodeIgniter 3] COOKIE的使用 PHP CodeIgniter 3 中COOKIE的使用超簡單

設定Google analytics API #1 -- Google網站上的設定 讓你的網站能夠存取你的Google analytics上面的資料

隨機好文

PHP for sphinx 函式庫安裝 PECL/sphinx PHP>= 5.2.2 已經能原生支援 sphinx,可是預設的沒有裝,我們得自己裝才能用

[Win7] 燒錄 iso 檔 在Windows7 中內建燒錄程式,可以直接把檔案拉到光碟機裡,再執行燒錄。

維修冰箱 維修冰箱

維修海棉拖把頭 這類型的海棉拖把很好用,可是這近發現海棉頭越來越不耐用,也許是錯覺,以往都能用個三四個月,現在二個月就差不多掉下來。 這

[大型機台] 熱血高校躲避球 多少少年時光歲月耗在這個遊戲上,二十幾年前的那個時光,唯一想做的事就是把吃飯錢省下來拿去打一場五塊錢的電動,就算是沒錢也