PHP在数组中创建组合

时间:2012-08-09 02:57:07

标签: php arrays implode

假设我有一个包含apples, watermelons, grapes的数组。我要做的是用

创建另一个数组

apples, apples;watermelons, apples;watermelons;grapes

我尝试使用内爆,但这并不是我想要的。这个任务有内置函数吗?谢谢!

编辑:为了澄清,创建的字符串基本上是这三个元素的组合。因此,创建的数组也可能如下所示:

apples, apples-watermelons, apples-watermelons-grapes

3 个答案:

答案 0 :(得分:2)

<?php
$my_array = array('apples','watermelons','grapes');
$string = '';
$result = array();
for ($i=0; $i<count($my_array); $i++) {
   $string .= $my_array[$i];
   $result[] = $string;
   $string .= '-';
}
print_r($result);

可能有办法使用array_walk()array_map()或其中一个array_*()函数来执行此操作。

答案 1 :(得分:2)

一种优雅的方法是使用array_reduce

<?php
$my_array = array('apples','watermelons','grapes');

function collapse($result, $item) {
    $result[] = end($result) !== FALSE ? end($result) . ';' . $item : $item;
    return $result;
}

$collapsed = array_reduce($my_array, "collapse", array());
var_dump($collapsed);
?>

测试:

matt@wraith:~/Dropbox/Public/StackOverflow$ php 11876147.php 
array(3) {
  [0]=>
  string(6) "apples"
  [1]=>
  string(18) "apples;watermelons"
  [2]=>
  string(25) "apples;watermelons;grapes"
}

答案 2 :(得分:1)

<?php

$array = array("apples", "watermelons", "grapes");
$newarray = $array;
for ($i = 1; $i < count($array); $i++)
{
   $newarray[$i] = $newarray[$i - 1] . ";" . $newarray[$i] ;
}

print_r($newarray);
?>

<强>输出:

Array
(
    [0] => apples
    [1] => apples;watermelons
    [2] => apples;watermelons;grapes
)