想知道这是否可行。 我有一个数组说
$colors = array( 'red', 'green' )
我想从上面的数组创建一个数组
$colors = array( 'red', 'red (2)', 'red (3)', 'red (4)','red (5)'
'green', 'green (2)', 'green (3)', 'green (4)', 'green (5)' );
我尝试过:
$a = array('red ','green');
print_r($a);
foreach( $a as $value ) {
for($i=0;$i<10;$i++) {
$b = array_pad($a, $i, $value.' ('.$i.')');
}
}
print_r($b);
答案 0 :(得分:3)
您可以使用简单的foreach
<?php
$colors = array( 'red', 'green' );
$new_colors = array();
echo "<pre>";
foreach($colors as $v)
{
$new_colors[] = $v;
foreach(range(2,5) as $v1)
{
$new_colors[]= $v." ( $v1 )";
}
}
print_r($new_colors);
<强> OUTPUT :
强>
Array
(
[0] => red
[1] => red ( 2 )
[2] => red ( 3 )
[3] => red ( 4 )
[4] => red ( 5 )
[5] => green
[6] => green ( 2 )
[7] => green ( 3 )
[8] => green ( 4 )
[9] => green ( 5 )
)
答案 1 :(得分:2)
$colors = array( 'red', 'green' );
for ($count=1; $count < 5; $count++) {
$sum = $count+1;
array_push($colors,"red($sum)");
array_push($colors,"green($sum)");
}
rsort($colors);
echo '<pre>';
print_r($colors);
echo '</pre>';
答案 2 :(得分:0)
您必须为此
执行自定义代码像
$colors = array( 'red', 'green' );
$newarray = array();
$count=0;
foreach($colors as $index=>$key)
{
for($i=0;$i<=5;$i++)
{
if($i>=2)
$newarray[$count++] = $key.' ('.$i.')';
else if($i==0)
$newarray[$count++] = $key;
}
}
echo '<pre>';
print_r($newarray);
输出:
Array
(
[0] => red
[1] => red (2)
[2] => red (3)
[3] => red (4)
[4] => red (5)
[5] => green
[6] => green (2)
[7] => green (3)
[8] => green (4)
[9] => green (5)
)
答案 3 :(得分:0)
一个简单的array_push就行了
$colors = array( 'red', 'green' );
$i=1;
for($i=1;$i<6;$i++)
{
array_push($colors,$colors[0].'('.$i.')');
array_push($colors,$colors[1].'('.$i.')');
}
print_r($colors);
?>
答案 4 :(得分:0)
/*
* array_repeat_values()
*
* repeate values of an array
*
* @param array $input
* @param int $multiplier
* @return array
*/
function array_repeat_values(array $input, $multiplier)
{
$r = array();
foreach($input as &$v)
for($i = 1; $i <= (int) $multiplier; ++$i) {
if($i < 2)
$r[] = $v;
else
$r[] = $v . " ($i)";
}
return $r;
}
$colors = array( 'red', 'green' );
var_dump(array_repeat_values($colors, 5));