2014-03-13 65 views
0

抱歉,如果標題有點混亂。
我被困在生成像這樣的數組。如何生成像二進制數字反轉陣列php

array(" one_third", " two_third", " two_third", " one_third", " one_third", " two_third", " two_third",..., " one_third", " one_third"); 

所以基本上我要像0, 1, 1, 0, 0, 1, 1, 0, 0數組如何生成在PHP或任何其他progaming語言。

我試圖

$ass = array(); 
    for($x = 0; $x <= 200; $x++){ 
    if($x == 0){ 
     array_push($ass, " one_third"); 
    }else if($x == 1){ 
     array_push($ass, " two_third"); 
    }else{ 
     if(count($ass) == 2){ 
     array_push($ass, " two_third"); 
     }else{ 
     if($ass[count($ass)-1] == " two_third" && $ass[count($ass)-2] == " two_third"){ 
      array_push($ass, " one_third"); 
     }else if($ass[count($ass)-1] == " one_third" && $ass[count($ass)-2] == " one_third"){ 
      array_push($ass, " two_third"); 
     } 
     } 
    } 
    } 

回答

0

你想使用模運算符。喜歡的東西:

<?php 
$ass = array(); 

for($x = 0; $x <= 200; $x++){ 
    if ($x == 0) { 
    array_push($ass, " one_third"); 
    } else { 
    if ($x % 2 == 0) { 
     array_push($ass, " one_third"); 
     array_push($ass, " one_third"); 
    } else { 
     array_push($ass, " two_third"); 
     array_push($ass, " two_third"); 
    } 
    } 
} 
print_r($ass); 
?> 
+0

almost..but它是輸出'陣列 ( [0] => one_third [1] => two_third [2] = > two_third [3] => one_third [4] => two_third [5] => two_third [6] => one_third ... [N] => two_third )' 只有一個「one_third」後雙「two_third」 –

+0

吶喊。對於那個很抱歉。編輯。 – cbrumsin

+0

真棒!謝謝你,你救了我的一天 –

0

你可能會考慮這樣做有違數組的每個值的函數並構造一個新數組的php.net/array_map功能。 「地圖」功能

http://en.wikipedia.org/wiki/Map_(higher-order_function)

$ar = array(" one_third", " two_third", " two_third", " one_third", " one_third", " two_third", " two_third", " one_third", " one_third"); 

$result = array_map(function($item) { 
    return (int) (trim($item) === "two_third"); 
    }, 
    $ar 
); 

var_export($result); 
0

有一個算法,其中可以傳遞具有可變大小的塊的陣列。 函數定義:

function getReversed($pieces, $length) { 
    $output = array(); 

    // prevent to execute empty array 
    if(empty($pieces)) 
     return $output; 

    for($i=0;$i<$length;$i++) { 
     $c = count($pieces); 
     $output[] = $pieces[(floor($i/$c)%2)?abs($i%$c-$c+1):($i%$c)]; 
    } 

    return $output; 
} 

幾個例子:

$test = array('a', 'b'); 
print_r(getReversed($test, 10)); 

// result: 

Array 
(
    [0] => a 
    [1] => b 
    [2] => b 
    [3] => a 
    [4] => a 
    [5] => b 
    [6] => b 
    [7] => a 
    [8] => a 
    [9] => b 
) 

$test = array('one', 'two', 'three'); 
print_r(getReversed($test, 8)); 

// result 
Array 
(
    [0] => one 
    [1] => two 
    [2] => three 
    [3] => three 
    [4] => two 
    [5] => one 
    [6] => one 
    [7] => two 
)