2013-03-29 68 views
0

我有幾個問題。得到這個數組:更有效地減數組

$array_1 = array(
    "1" => "4", 
    "2" => "8", 
    "3" => "12", 
    "4" => "16", 
    "5" => "20", 
    "6" => "24", 
    "7" => "28", 
    "8" => "32", 
    "9" => "36", 
    "10" => "40", 
    "11" => "44", 
    "12" => "48", 
    "13" => "52", 
    "14" => "56", 
    "15" => "60", 
    "16" => "64", 
    "17" => "68", 
    "18" => "72", 
    "19" => "76", 
    "20" => "80", 
    "21" => "84", 
    "22" => "88", 
    "23" => "92", 
    "24" => "96", 
    "25" => "100", 
    "26" => "104", 
    "27" => "108", 
    "28" => "112", 
    "29" => "116", 
    "20" => "120", 
    "31" => "124", 
    "32" => "128", 
    "33" => "132", 
    "34" => "136", 
    "35" => "140", 
    "36" => "144", 
    "37" => "148", 
    "38" => "152", 
    "39" => "156", 
    "40" => "160", 
    "41" => "164", 
    "42" => "168", 
    "43" => "172", 
    "44" => "176", 
    "45" => "180", 
    "46" => "184", 
    "47" => "188", 
    "48" => "192", 
    "49" => "196", 
    "50" => "200" 
); 

我想通過1,2,3,4減去$array_1到多個數組中。到目前爲止,我已經具有其他陣列做到了:

$array_2 = array(
    "1" => "1", 
    "2" => "1", 
    ... 
    "49" => "1", 
    "50" => "1" 
); 

$array_3 = array(
    "1" => "2", 
    "2" => "2", 
    ... 
    "49" => "2", 
    "50" => "2" 
); 
// All the way to values of 4 

然後用這個,我會做一個array_diff得到降低的值。

我想知道首先有一個更好的方法(更有效率)減少數組而不是重複1,2,3,4每個50次。

其次,有沒有更有效的方法讓$array_1的值爲4的倍數達到200?

第三,我是否需要一個數組來減去$array_1以降低數值?有沒有更好的方式來此類似:$array_1 - 1

預期輸出

// $array_1 - $array_2 (value of 1) 
$minus_one = array(
    "1" => "3", 
    "2" => "7", 
    "3" => "11", 
    ... 
); 
// $array_1 - $array_3 (value of 2) 
$minus_two = array(
    "1" => "2", 
    "2" => "6", 
    "3" => "10", 
    ... 
); 
// $array_1 - $array_4 (value of 3) 
$minus_one = array(
    "1" => "1", 
    "2" => "4", 
    "3" => "8", 
    ... 
); 
+1

不能理解,你能告訴我你想要的輸出嗎? – rohitarora

+0

@rohitarora補充說:] – Ahhhhhhhhhhhhhdfgbv

回答

3

雖然xdazz是解決方案是正確的。你也可以直接生成最終的預期數組

$array_1 = array_fill(1, 50, null); 
array_walk($array_1, function(&$item, $key){ 
    $item = $key * 4; 
}); 

$minus_one = $minus_two = $minus_three = array(); 
foreach($array_1 as $key => $value) 
{ 
    $minus_one[$key] = $value - 1 ; 
    $minus_two[$key] = $value - 2 ; 
    $minus_three[$key] = $value - 3 ; 
} 
+0

這個效果很好!我想知道如果一個值是在$ key中的一箇中,我該如何找到它? '$ c = 4; if($ c == $ minus_one){...}'其中'$ c'不是一個數組。 – Ahhhhhhhhhhhhhdfgbv

+0

你可以使用'array_key_exists($ value,$ minus_one)' –

+0

不知道那個!乾杯:] – Ahhhhhhhhhhhhhdfgbv

2

你可以構建你的陣列象下面這樣:

$array_1 = array_fill(1, 50, null); 
array_walk($array_1, function(&$item, $key){ 
    $item = $key * 4; 
}); 
var_dump($array_1); 

$array_2$array_3,只是使用array_fill足夠:

$array_2 = array_fill(1, 50, 1); 
$array_3 = array_fill(1, 50, 2); 
+0

本來應該標明這是正確的,但kuldeep.kamboj有點釘了它。 – Ahhhhhhhhhhhhhdfgbv