抱歉,如果标题有点令人困惑。
我被困在生成这样的数组。
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或任何其他编程语言中生成它。
我试过
$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 :(得分: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);
?>
答案 1 :(得分:0)
您可以查看php.net/array_map函数,该函数针对数组的每个值运行函数并构造新数组。 &#34;地图&#34;功能
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);
答案 2 :(得分: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
)