Let's say I have an array containing: apples, watermelons, grapes
. What I'm trying to do is create another array with
apples, apples;watermelons, apples;watermelons;grapes
I tried using implode, but it's not exactly what I wanted. Is there a built in function for this task? Thanks!
EDIT: For clarification, the created string is basically a combination of these three elements. So the created array could also look like:
apples, apples-watermelons, apples-watermelons-grapes
<?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);
There may be a way to do it with array_walk()
or array_map()
or one of the other array_*()
functions as well.
An elegant way to do it is with 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);
?>
Testing:
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"
}
<?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);
?>
Output:
Array
(
[0] => apples
[1] => apples;watermelons
[2] => apples;watermelons;grapes
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.