note 74011 added to function.implode
| From: | darwinkid at gmail dot com | Date: | Tue, 20 Mar 2007 20:09:59 +0000 |
| Subject: | note 74011 added to function.implode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-124644@lists.php.net to get a copy of this message | ||
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)
{
// create a new recursive iterator to get array items
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($pieces));
$arr = array();
foreach($it AS $element) {
if ($it->key() == $keyname) {
$arr[] = $it->current();
}
}
return implode($glue, $arr);
}
// here is an example
$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
----
Server IP: 64.71.164.2
Probable Submitter: 216.136.83.245
----
Manual Page -- http://www.php.net/manual/en/function.implode.php
Edit -- https://master.php.net/note/edit/74011
Del: integrated -- https://master.php.net/note/delete/74011/integrated
Del: useless -- https://master.php.net/note/delete/74011/useless
Del: bad code -- https://master.php.net/note/delete/74011/bad+code
Del: spam -- https://master.php.net/note/delete/74011/spam
Del: non-english -- https://master.php.net/note/delete/74011/non-english
Del: in docs -- https://master.php.net/note/delete/74011/in+docs
Del: other reasons-- https://master.php.net/note/delete/74011
Reject -- https://master.php.net/note/reject/74011
Search -- https://master.php.net/manage/user-notes.php