2011-01-08 47 views
0

我想通過定義一個鍵來創建一個基於另一個數組值的數組?通過定義一個鍵來基於另一個數組值創建一個數組?

E.g.

$old_array = array('hey', 'you', 'testing', 'this'); 

function get_new_array($key) { 
global $old_array; 

//return new array... 
} 

$new_array = get_new_array(2); //would return array('hey, 'you', 'testing'); as its the values of all the keys before the key 2 and the 2 key itself 

感謝所有幫助! :B

+2

如果你打算把它放在一個自定義的函數中,我覺得使用`global`是個好主意。 – BoltClock 2011-01-08 01:38:22

回答

2

使用array_slice()

function get_new_array($key) { 
    global $old_array; 
    return array_slice($old_array, 0, $key+1); 
} 

幾點建議:

  • 你想子陣列最多返回和包括的關鍵。取而代之的是不包括的關鍵。因此+1是necassary。
  • 使用$old_array作爲一個全球性很差的風格。我建議將它作爲參數傳遞給函數。
  • 由於array_slice()已經做了你想要的,除了小的差異,我會直接調用它,而不是寫一個隱藏功能的包裝函數。
+0

+1我在原始問題中看到的`global`讓我感到不安... – BoltClock 2011-01-08 01:37:15

+0

@BoltClock正在編輯:) – marcog 2011-01-08 01:39:56

1
$new=array_slice($old_array,0,3); 
0

使用array_slice()函數:

$input = array("a", "b", "c", "d", "e"); 

$output = array_slice($input, 2);  // returns "c", "d", and "e" 
$output = array_slice($input, -2, 1); // returns "d" 
$output = array_slice($input, 0, 3); // returns "a", "b", and "c" 

鏈接manual

相關問題