2010-10-06 44 views
1

有沒有更好的方式在PHP中以三個一組的方式訪問此數組?如何從數組中檢索數據,每次3個?

比方說,我的陣列是用逗號分隔的字符串,如:

("Thora","Birch","Herself","Franklin Delano","Roosevelt","Himself (archive footage)","Martin Luther","King","Himself (archive footage) (uncredited)") 

雖然陣列可最終被大得多,每一個將在三個邏輯組不同,但仍然(名字,姓氏,角色)。

我試圖做到的是通過三個一組的數組循環,從而使第一記錄將具有firstname[0]=>"Thora", lastname[0]=>"Birch" and role[0]=>"Herself".

我只用foreach循環,但沒有看到一個額外的參數一樣「對於每個3」,也許有人可以擺脫一些光線?

+0

你必須使用()步驟3,我不知道,直接做的任何功能。 – MatTheCat 2010-10-06 14:29:10

回答

4

PHP如何有一個名爲array_chunk專爲這項任務功能。

試試這個:

$sets = array_chunk($people, 3); 
foreach ($sets as $set) { 
    //you could use the following line to put each field into a nice variable 
    list ($firstname, $lastName, $role) = $set; 

    //if all you want to do is collect the values, do this 
    $firstNames[] = $set[0]; 
    $lastNames[] = $set[1]; 
    $role[] = $set[2]; 
} 

注意,最後一個塊可能不是大小爲3,所以你應該檢查鍵1和2都設置有isset,如果你不能保證你的陣列總是3的倍數。

+0

請確保以塊大小調用array_chunk:array_chunk($ people,3) – 2010-10-06 14:58:39

+0

糟糕 - 謝謝! – 2010-10-06 14:59:34

+0

這是我沒有聽說過的,謝謝你的幫助!我將在明天讓這個運行,看起來不錯,優雅! – Chris 2010-10-07 06:31:49

2

爲此,您可以使用for -loop,假設您的'人員'數組的長度爲3n

$people = array("Thora","Birch","Herself","Franklin Delano","Roosevelt","Himself (archive footage)","Martin Luther","King","Himself (archive footage) (uncredited)"); 
$firstName = array(); 
$lastName = array(); 
$role = array(); 
for($i=0; $i<count($people); $i += 3){ 
    $firstName[] = $people[$i]; 
    $lastName[] = $people[$i+1]; 
    $role[] = $people[$i+2]; 
} 
1

約 僞代碼

for Index = 0 index = length index +=3 
{ 
    Firstname= array[index] 
    middlename = array[index+1] 
    lastname = array[index+2] 
    Do Something with them... 
} 
+0

我不是一個PHP程序員,但我無法想象這不是完全按照要求提供的。 – 2010-10-07 00:42:50

1

另外,如果你使用PHP> = 5.3:

array_walk(
     range(1,9),//<== normally your array, range(1,9) is just an example/test value 
     function($value,$key) use (&$return){ 
       $return[$key % 3][] = $value; 
     }); 
var_dump($return); 
相關問題