1

我想要这些数组...

array('bread','jelly','olive');
array('chocolate','chip');

成为这些阵列...

array('bread','bread','jelly','jelly','olive','olive');
array('chocolate','chocolate','chip','chip');

是否有捷径可寻?

4

5 回答 5

2
$myarray = array('bread','jelly','olive');
$mynewarray = array_merge($myarray, $myarray);
sort($mynewarray);
var_dump($mynewarray);

输出:

array(6) {
  [0]=>
  string(5) "bread"
  [1]=>
  string(5) "bread"
  [2]=>
  string(5) "jelly"
  [3]=>
  string(5) "jelly"
  [4]=>
  string(5) "olive"
  [5]=>
  string(5) "olive"
}
于 2013-01-08T18:55:10.710 回答
2
function duplicateItems(array $inputArray, $n = 2) {
    $result = array();
    foreach ($inputArray as $value) {
        for ($i = 0; $i < $n; $i++) {
            $result[] = $value;
        }
    }
    return $result;
}

用法:

$duplicateArray = duplicateItems(array('bread', 'jelly', 'olive'));
于 2013-01-08T18:53:51.960 回答
1

Use array_splice() Works really fast, because no sorting is involved.

$a = array('bread','jelly','olive');
$i=0;
foreach ($a as $b) {
    array_splice($a,$i*2,0,$b);
    $i++;
}
于 2013-01-08T19:05:26.083 回答
0

如果这可行: array('bread','jelly','olive',bread','jelly',''olive');

 $array = array('bread','jelly','olive');
 $array = array_merge($array, $array);

然后你可以按字母顺序排序:

 sort($array);
于 2013-01-08T18:55:59.107 回答
0

你可以这样做:

$singleValues = array('bread','jelly','olive');
$newArray = array();
foreach ($singleValues as $value) {
   $newArray[] = $value;
   $newArray[] = $value;
}
于 2013-01-08T18:53:58.427 回答