2014-03-13 68 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 
)