note 78332 deleted from function.implode by hholzgra
| From: | hholzgra@php.net | Date: | Thu, 02 Aug 2012 13:19:10 +0000 |
| Subject: | note 78332 deleted from function.implode by hholzgra | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-189745@lists.php.net to get a copy of this message | ||
Note Submitter: sinatosk at gmail dot com
----
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 ;)