|
|
implode (PHP 3, PHP 4, PHP 5) implode -- Объединяет элементы массива в строку Описаниеstring implode ( string glue, array pieces )
Возвращает строку, полученную объединением строковых представлений
элементов массива pieces, со вставкой строки
glue между соседними элементами.
Пример 1. Пример использования implode() |
<?php
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; ?>
|
|
Замечание:
По историческим причинам, функции implode() можно
передавать аргументы в любом порядке, однако для унификации с
функцией explode() следует использовать
документированный порядок аргументов.
Замечание:
Начиная с версии 4.3.0 аргумент glue функции
implode() является необязательным и по умолчанию
равен пустой строке (''). Для обеспечении обратной совместимости
рекомендуется всегда передавать оба аргумента.
Замечание: Эта функция безопасна
для обработки данных в двоичной форме.
См. также описания функций explode() и
split().
anajilly
31-Oct-2007 12:23
When implode() is passed an array with a single element or
with no elements, it does exactly what you would expect.
<?php
$a = array(); implode(';', $a); $a[] = 'n'; implode(';', $a); ?>
1413 at blargh dot com
10-Oct-2007 03:42
Below is the function for making an English-style list from an array, seems to be simpler than some of the other examples I've seen.
<?php
function ImplodeProper($arr, $lastConnector = 'and')
{
if( !is_array($arr) or count($arr) == 0) return '';
$last = array_pop($arr);
if(count($arr))
return implode(', ',$arr).", $lastConnector $last";
else
return $last;
}
?>
Examples:
<?
print ImplodeProper(array()).'<br>';
print ImplodeProper(array('foo')).'<br>';
print ImplodeProper(array('foo','bar')).'<br>';
print ImplodeProper(array('for','bar','bleh')).'<br>';
?>
Yields:
foo
foo, and bar
for, bar, and bleh
sinatosk at gmail dot com
07-Oct-2007 05:42
This code implodes same as the PHP built in except it allows you to do multi dimension arrays ( similar to a function below but works dynamic :p.
<?php
function implode_md($glue, $array, $array_path='')
{
if ( !empty($array_path) )
{
$array_path = explode('.', $array_path);
if ( ( $array_path_sizeof = sizeof($array_path) ) < 1 )
{
return implode($glue, $array);
}
}
else
{
return implode($glue, $array);
}
$str = '';
$array_sizeof = sizeof($array) - 1;
for ( $i = 0; $i < $array_sizeof; $i++ )
{
$value = $array[ $i ];
for ( $j = 0; $j < $array_path_sizeof; $j++ )
{
$value =& $value[ $array_path[ $j ] ];
}
$str .= $value . $glue;
}
$value = $array[ $array_sizeof ];
for ( $j = 0; $j < $array_path_sizeof; $j++ )
{
$value =& $value[ $array_path[ $j ] ];
}
$str .= $value;
return $str;
}
?>
And heres an example on how to use this
<?php
$arr = array();
$arr[]['data']['id'] = 'a';
$arr[]['data']['id'] = 'b';
$arr[]['data']['id'] = 'c';
$arr[]['data']['id'] = 'd';
$arr[]['data']['id'] = 'e';
$arr[]['data']['id'] = 'f';
$arr[]['data']['id'] = 'g';
echo implode_md(',', $arr, 'data.id');
?>
The output of this code should be
'a,b,c,d,e,f,g'
When you want to work with more dimensions... say for example you have an array that is like this
<?php
$arr=array();
$arr[0]['game']['pc']['fps']['idsoftware'] = 'Quake';
$arr[1]['game']['pc']['fps']['idsoftware'] = 'Quake II';
$arr[2]['game']['pc']['fps']['idsoftware'] = 'Quake III Arena';
?>
on the third parameter... as a string you simply type in
<?php
echo implode_md(', ', $arr, 'game.pc.fps.idsoftware');
?>
and the output should be
'Quake, Quake II, Quake III Arena'
Enjoy ;)
thomas at tgohome dot com
09-Jul-2007 01:05
This is my quick function to create a list, English style, but will accept any glue, so you could use 'or', or even 'or though, it could be', etcetera. It should also support PHP 4, although I haven't tested it; it doesn't use the PHP 5 negative substr() trick.
<?php
function implode_ea($glue_punct, $glue_word, $array) {
$result = implode($glue_punct, $array);
if(count($array) > 1) {
$trimamount = strlen($array[count($array) - 1]) + strlen($glue_punct);
$result = substr($result, 0, strlen($result) - $trimamount); $result = "$result $glue_word " . $array[count($array) - 1];
return $result;
} else {
return $result;
}
}
echo implode_ea(", ", "and", array("one", "two", "three"));
?>
(implode_ea stands for 'Implode, English And style')
Hope this helps,
Tom
peter dot goodman at gmail dot com
04-Jul-2007 10:36
I came up with this nifty function to implode an Iterator or class that implements IteratorAggregate:
function implode_iterator($sep = '', $it) {
$a = array();
if(!$it instanceof Traversable) {
throw new UnexpectedValueException('$it must implement Traversable.');
}
if($it instanceof IteratorAggregate) {
$a = iterator_to_array($it, FALSE);
} else if($it instanceof Iterator) {
foreach($it as $val) {
$a[] = $val;
}
}
return implode($sep, $a);
}
Dennis Day
02-Jul-2007 02:39
I have resolved an issue in SquirrelMail. The problem seemed to be with the implode command. Apparently you do not want to use this function with a large array as SquirellMail attempted to do. This only was an issue with some of the email attachments larger that 2MB.
In /src/move_messages.php, replace the line line that says
$body = implode('', $body_a);
With :
// Dennis Day's custom code
$body = "";
foreach($body_a as $body_a_key=>$body_a_value){
$body .= $body_a_value;
}
// End Dennis Day's custom code
// Original Bad Code
// $body = implode('', $body_a);
troy dot cregger at gmail dot com
15-Jun-2007 10:42
Concerning the function by: darwinkid at gmail dot com... Nice one, I found it useful.
I made a modification to it though to handle array keys of the form:
array(
[key1] => one
[key2] => two
[key3] => three
)
It also discards empty elements in the array so if you have:
array(
[key1] => one
[key2] => two
[key3] => three
[key4] =>
[key5] => five
)
You'd get:
one,two,three,five
rather than:
one, two, three, ,five
If you supply ", " as glue.
Here's my code:
<?php
function my_implode_by_key($glue, $key, $pieces) {
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($pieces));
foreach($it as $el) {if(substr($it->key(), 0, 3) == $key && $it->current() != '') {$arr[] = $it->current();}}
return implode($glue, $arr);
}
?>
troy dot cregger at gmail dot com
15-Jun-2007 10:36
Concerning the function by: darwinkid at gmail dot com... Nice one, I found it useful.
I made a modification to it though to handle array keys of the form:
array(
[key1] => one
[key2] => two
[key3] => three
)
It also discards empty elements in the array so if you have:
array(
[key1] => one
[key2] => two
[key3] => three
[key4] =>
[key5] => five
)
You'd get:
one,two,three,five
rather than:
one, two, three, ,five
If you supply ", " as glue.
Here's my code:
<?php
function my_implode_by_key($glue, $key, $pieces) {
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($pieces));
foreach($it as $el) {if(substr($it->key(), 0, 3) == $key && $it->current() != '') {$arr[] = $it->current();}}
return implode($glue, $arr);
}
?>
TheMadBomberWhatBombsAtMidnight
14-Jun-2007 08:46
in response to Brian, building a POST/GET string from an assoc array is easily done with the builtin http_build_query...as the example from its doc page shows:
<?php
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
echo http_build_query($data); ?>
of course, the builtin function also urlencodes the string it returns, which Brian's function did not.
Brian
12-Jun-2007 01:42
A simple extension to implode, which includes a second gluing of keys. Particularly handy when managing $_GET and $_POST.
<?
function implode_assoc($glue1, $glue2, $array){
foreach($array as $key => $val)
$array2[] = $key.$glue1.$val;
return implode($glue2, $array2);
}
//usage:
$array["key"]="val";
$array["key2"]="val2";
implode_assoc("=", "&", $array); //returns "key=val&key2=val2"
?>
darwinkid at gmail dot com
20-Mar-2007 01:09
this is a little function i made to implode an array based on key. its main purpose is to implode elements within
a multi-dimensional array. its slightly different than some of the other examples because it makes use of some
PHP SPL features. if your not using PHP5, this definitely won't work for you.
let me know what you think!
<?php
function implode_by_key($glue, $keyname, $pieces)
{
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($pieces));
$arr = array();
foreach($it AS $element) {
if ($it->key() == $keyname) {
$arr[] = $it->current();
}
}
return implode($glue, $arr);
}
$array = array(
array('somekey' => 'somevalue'),
array(
array('key2' => 'anoter value'),
array('key2' => 'another sub value'),
array(
array('key3' => 'asdlkfs jdafajdshf aoufiahsdlkfjsadf'),
array(
array('key4' => 'this is key 4 - 1'),
array('key4' => 'this is key 4 - 2'),
array('key4' => 'this is key 4 - 3'),
array(
array('key5' => 'asdfkajsdflkasjdfklajshfkljasfhasdfasdf'),
array('key5' => 'asdfkajsdflkasjdfklajshfkljasfhasdfasdf'),
)
)
)
)
);
echo implode_by_key('<br/>', 'key4', $array);
?>
This outputs:
this is key 4 - 1
this is key 4 - 2
this is key 4 - 3
Hayley
19-Mar-2007 03:52
And adding one more case to drewish at katherinehouse dot com's code to deal with the two-element case "a and b":
<?php
case 2:
return reset($array).' and '.end($array);
?>
Of course, then one can start considering Oxford rules again, and maybe testing that the argument really is an array....
<?php
function english_list($array, $useOxfordComma=false)
{
if(!is_array($array))
return '';
switch(count($array))
{
case 0:
return '';
case 1:
return reset($array);
case 2:
return reset($array).' and '.end($array);
default:
$last = array_pop($array);
return implode(', ', $array).($useOxfordComma?',':'').' and '.$last;
}
}
?>
drewish at katherinehouse dot com
10-Jan-2007 08:07
Here's a pretty clean version of the english_list:
<?php
function english_list($array) {
switch (count($array)) {
case 0:
return '';
case 1:
return array_pop($array);
default:
$last = array_pop($array);
return implode(', ', $array) . ' and ' . $last;
}
}
?>
ahigerd at stratitec dot com
04-Jan-2007 06:43
Note that PHP uses copy-on-write so passing parameters (even array parameters) by reference gains you no performance benefit, and in fact in some cases can HURT performance.
For example:
php > $array = array('a','s','d','f');
php > $start = microtime(true); for($i=0; $i<1000000; $i++) byref($array); echo microtime(true)-$start;
2.40807890892
php > $start = microtime(true); for($i=0; $i<1000000; $i++) byval($array); echo microtime(true)-$start;
1.40822386742
bishop
23-Nov-2006 06:33
The english_list() implementation of davidpk212 at gmail dot com, Andy Morris, and tshort at cisco dot com does not handle the case of a two-element array with Oxford comma. Example:
<?php
english_list(array ('a', 'b'), true) ?>
Here's another implementation that addresses this issue, uses pass-by-reference without modifying the array, and illustrates yet another approach to solving the problem:
<?php
function english_list(&$array, $useOxfordComma = false) {
$count = (is_array($array) ? count($array) : 0);
if (3 <= $count) {
$last = end($array);
$list = prev($array) . ($useOxfordComma ? ', and ' : ' and ') . $last;
while ($v = prev($array)) {
$list = $v . ', ' . $list;
}
} else if (2 == $count) {
$last = end($array);
$list = prev($array) . ' and ' . $last;
} else if (1 == $count) {
$list = end($array);
} else {
return '';
}
reset($array);
return $list;
}
?>
Run times for this version are comparable to the run times for heir earlier posted versions.
richard at happymango dot me dot uk
23-Nov-2006 04:43
This is a simple function that is the same as implode except it allows you to specify two glue parameters instead of one so an imploded array would output "this, this, this and this" rather than "this, this, this, this, this".
This is useful if you want to implode arrays into a string to echo as part of a sentence.
It uses the second glue between the last two items and the first glue between all others. It will use the second glue if there are only two items to implode so it would output "this and this".
<?php
function implode2($glue1, $glue2, $array)
{
return ((sizeof($array) > 2)? implode($glue1, array_slice($array, 0, -2)).$glue1 : "").implode($glue2, array_slice($array, -2));
}
$array = array("Monday", "Tuesday");
echo "1: ".implode2(', ', ' and ', $array)."<br />";
$array = array("Mon", "Tue", "Wed", "Thu", "Fri");
echo "2: ".implode2(', ', ' & ', $array)."<br />";
$array = array( 1, 2, 3, 4, 10);
echo "3: ".implode2(' + ', ' = ', $array)."<br />";
?>
This outputs
1: Monday and Tuesday
2: Mon, Tue, Wed, Thu & Fri
3: 1 + 2 + 3 + 4 = 10
Demonisch
05-Oct-2006 02:11
Very simple function for imploding a certain column in a 2D array. Useful if you have fetched records from a database in an associative array and want to store all the values in a certain column as a string, for use with JavaScript or passing values from page to page.
$sep = the separator, such as " ", "," or "&"
$array = the 2D associative array
$key = the column key, such as "id"
Feel free to add error protection
function implodeArray2D ($sep, $array, $key)
{
$num = count($array);
$str = "";
for ($i = 0; $i < $num; $i++)
{
if ($i)
{
$str .= $sep;
}
$str .= $array[$i][$key];
}
return $str;
}
triptripon at gmail dot com
05-Sep-2006 02:18
Here's my 2 matching (implode|explode)_with_key functions.
Notice, the inglue, outglue cannot appear within the keys\values.
function implode_with_key($assoc, $inglue = '>', $outglue = ',')
{
$return = '';
foreach ($assoc as $tk => $tv)
{
$return .= $outglue . $tk . $inglue . $tv;
}
return substr($return,strlen($outglue));
}
function explode_with_key($str, $inglue = ">", $outglue = ',')
{
$hash = array();
foreach (explode($outglue, $str) as $pair)
{
$k2v = explode($inglue, $pair);
$hash[$k2v[0]] = $k2v[1];
}
return $hash;
}
-- Tomer Levinboim
worldwideweb dot C-Kling dot de
12-Aug-2006 12:15
A Script for imploding a multideimensional Array. You give an array of separators in the first argument, and a (multidimensional) array in the second. The script will return the imploded array.
<?php
function multimplode($spacer,$array)
{
if (!is_array($array))
{
return($array);
}
if (empty($spacer))
{
return(multimplode(array(""),$array));
}
else
{
$trenn=array_shift($spacer);
while (list($key,$val) = each($array))
{
if (is_array($val))
{
$array[$key]=multimplode($spacer,$val);
}
}
$array=implode($trenn,$array);
return($array);
}
}
?>
adnan at barakatdesigns dot net
23-May-2006 09:17
An easier way of achieving the same result as implode_with_keys() - and quicker execution time:
<?
/* NOTE: $glue is not used if $is_query is true */
function implode_with_keys($array, $glue, $is_query = false) {
if($is_query == true) {
return str_replace(array('[', ']', '&'), array('%5B', '%5D', '&'), http_build_query($array));
} else {
return urldecode(str_replace("&", $glue, http_build_query($array)));
}
}
echo implode_with_keys(array('a[1]' => 'some text', 'a[2]' => 'even more text'), false, true);
/* Will output 'a%5B1%5D=some+text&a%5B2%5D=even+more+text' */
/* This won't break html validation */
echo implode_with_keys(array('a[1]' => 'foo bar', 'b' => 'more text'), '|');
/* Will output 'a[1]=foo bar|b=more text' */
?>
dabduster at gmail dot com
03-Jan-2006 08:39
an implementation of adrian at foeder dot de implode_with_keys function for input and update sql statement.
function implode_param($glue, $array, $valwrap='', $mode = 0)
{
/*
if mode = 0 output is key and values
if mode = 1 output only keys
if mode = 2 output only values
*/
switch ($mode){
case 1:
foreach($array AS $key => $value) {
$ret[] = $valwrap.$key.$valwrap;
}
break;
case 2:
foreach($array AS $key => $value) {
$ret[] = $valwrap.$value.$valwrap;
}
break;
default:
case 0:
foreach($array AS $key => $value) {
$ret[] = $key."=".$valwrap.$value.$valwrap;
}
break;
}
return implode($glue, $ret);
}
Hotmail resident Tree2054
08-Dec-2005 11:57
Combining into one function:
function implode_with_options($assoc_array, $prefix = '', $k_v_glue = '', $vwrap = '', $seperator = '')
{
foreach ($assoc_array as $k => $v)
{
$tmp[] = $k . $k_v_glue . $vwrap . $v . $vwrap;
}
return $prefix . implode($seperator, $tmp);
}
$items = array('Apples', 'number' => 3, 'Vehicle' => '');
// For a query string:
echo implode_with_options($items, '?', '=', '', '&');
/**
* Produces
* ?0=Apples&number=3&Vehicle=
*/
// For a SQL query
echo implode_with_options($items, '', '=', '"', ', ');
/**
* Produces
* 0="Apples", number="3", Vehicle=""
*/
adrian at foeder dot de
31-Oct-2005 04:53
...and a mysql-update-statement-compatible implementation of implode_with_keys:
<?php
function implode_with_keys($glue, $array, $valwrap='')
{
foreach($array AS $key => $value) {
$ret[] = $key."=".$valwrap.$value.$valwrap;
}
return implode($glue, $ret);
}
?>
so implode_with_keys(", ", $array, "'") will output:
key1='value1', key2='value2'
and so on. Useful for UPDATE table SET key1='value1', key2='value2'
Peter Hopfgartner
27-Sep-2005 07:26
Correctly initializing all variables, this would become:
function implode_with_key($assoc, $inglue = '=', $outglue = '&'){
$return = '';
foreach ($assoc as $tk => $tv) {
$return = ($return != '' ? $return . $outglue : '') .
$tk . $inglue . $tv;
}
return $return;
}
Note, the return value is also well defined if $assoc is empty.
Regards
php at josh dot jeppsons dot org
09-Sep-2005 09:22
Another variation on implode_with_key:
<?php
function implode_with_key($assoc, $inglue = '=', $outglue = '&')
foreach ($assoc as $tk => $tv) {
$return = (isset($return) ? $return . $outglue : '') . $tk . $inglue . $tv;
}
return $return;
}
?>
pr10n at spymac dot com
29-Aug-2005 09:46
A little tweak on info at urbits dot com's suggestion just incase someone changes their value of $outglue:
<?php
function implode_with_key($assoc, $inglue = '=', $outglue = '&')
{
$return = null;
foreach ($assoc as $tk => $tv) $return .= $outglue.$tk.$inglue.$tv;
return substr($return,strlen($outglue));
}
?>
info at urbits dot com
19-Aug-2005 06:06
I liked memandeemail's (27-Apr-2005) neat code for imploding an associative array. I have done a mod so that, by default, it returns a url query string.
<?php
function implode_with_key($assoc, $inglue = '=', $outglue = '&')
{
$return = null;
foreach ($assoc as $tk => $tv) $return .= $outglue.$tk.$inglue.$tv;
return substr($return,1);
}
?>
Example:
<?php
$assoc_array = array("a" => "foo", "b" => "bar", "c" => "foobar");
echo (implode_with_key($assoc_array);
?>
ouput: a=foo&b=bar&c=foobar
usage: After altering the $HTTP_GET_VARS values, I pass $HTTP_GET_VARS to the function to easily build variation urls for links and header redirects.
note: This function doesn't encode the url string or check for empty variables.
cristianDOTzuddas [AT] gmailDOTcom
07-Jul-2005 12:22
...and another variation of "implode_assoc" function. Just added the boolean parameter $urlencoded; if TRUE returns the array value in URL encod format. If the parameter is not given it behaves like the original function.
<?
function implode_assoc($inner_glue, $outer_glue, $array, $skip_empty=false, $urlencoded=false) {
$output = array();
foreach($array as $key=>$item) {
if (!$skip_empty || isset($item)) {
if ($urlencoded)
$output[] = $key.$inner_glue.urlencode($item);
else
$output[] = $key.$inner_glue.$item;
}
}
return implode($outer_glue, $output);
}
?>
sam dot bledsoe at nosp at nn dot gmail dot com
31-May-2005 08:57
The function below recursively outputs an array in a format condusive to parsing it in php or another scripting language. It does NOT output the name of the original array, for that see note 1. It handles all the cases I could think of elegantly. Comments and criticisms are welcome.
For an array constructed with:
$arr = array("foo" => array('bar' => array(0 => "value 0", 1 => "value 1")), "foo two" => array(0 => array("bar" => "value2")));
The line below:
echo implode_parseable("=", ";<br>$", $arr, "$", ";");
Will produce:
$foo["bar"][0]="value 0";
$foo["bar"][1]="value 1";
$foo_two[0]["bar"]="value2";
NOTES:
1) If the leading identifier on a line is a number, the output will most likely be unusable since variable names cannot begin with numbers. You can get around this by doing something like:
$arr = array('arr' => $arr);
This will output the array as it actually is (because the key is the same name as the array) instead of just its fields.
2) Since spaces are not allowed in variable names, they are replaced in lines' leading identifiers by the $space_replace_char parameter, '_' by default.
Hopefully someone will find this useful, if so drop me a line. Credit and thanks go out to the people who posted their code on this manual page, especially davidpk212 at gmail dot com and phpWalter at torres dot ws.
function implode_parseable($inner_glue = "=", $outer_glue = "\n", $array = null, $prefix = "", $suffix = "", $space_replace_char = '_', $skip_empty = false, $current_loc = "", $recursion_level = 0){
return $prefix . implode_parseable_r($inner_glue, $outer_glue, $array, $space_replace_char, $skip_empty, $current_loc, $recursion_level) . $suffix;
}
function implode_parseable_r($inner_glue = "=", $outer_glue = "\n", $array = null, $space_replace_char = '_', $skip_empty = false, $current_loc = "", $recursion_level = 0)
{
if(is_array($array)){
$output = array();
foreach( $array as $key => $item ){
if ( is_array ($item) ){
//don't quote numeric indicies
if(is_string($key))
$quoted_key = "\"" . $key . "\"";
else
$quoted_key = $key;
// This is value is an array, go and do it again!
$level = $recursion_level + 1;
if($recursion_level == 0){
// can't have spaces in a variable name!
$current_loc .= str_replace(' ', $space_replace_char, $key);
$output[] = implode_parseable_r ($inner_glue, $outer_glue, $item, '_', $skip_empty, $current_loc, $level);
//start the position tracker over after every run from level 0
$current_loc = '';
}else{
$current_loc .= "[" . $quoted_key . "]";
$output[] = implode_parseable_r ($inner_glue, $outer_glue, $item, '_', $skip_empty, $current_loc, $level);
//remove the last index from the position tracker string after using it
$current_loc = ereg_replace('\[[^]]*\]$', '', $current_loc);
}
}
else{
// don't quote or []ify the base variable name,
// but do for all else as appropriate
if($recursion_level != 0){
if(is_string($key))
$key = "\"" . $key . "\"";
$key = "[" . $key . "]";
}
// echo "<br>";
// var_dump($item);
// echo "<br>";
$skip_this = false;
if($skip_empty && (!isset($item) || $item == NULL || $item == '')) $skip_this = true;
//quote the item (which is the value of the array index) if it is a string
if(is_string($item)) $item = "\"" . $item . "\"";
if(!$skip_this) $output[] = $current_loc . $key . $inner_glue . $item;
}
}
return implode($outer_glue, $output);
}else{
return $array;
}
}
|