note 78332 added to function.implode

From: Date: Sun, 07 Oct 2007 12:42:37 +0000
Subject: note 78332 added to function.implode
Groups: php.notes 
Request: Send a blank email to php-notes+get-131195@lists.php.net to get a copy of this message
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 ;) ---- Server IP: 194.145.210.3 Probable Submitter: 86.15.194.172 ---- Manual Page -- http://www.php.net/manual/en/function.implode.php Edit -- https://master.php.net/note/edit/78332 Del: integrated -- https://master.php.net/note/delete/78332/integrated Del: useless -- https://master.php.net/note/delete/78332/useless Del: bad code -- https://master.php.net/note/delete/78332/bad+code Del: spam -- https://master.php.net/note/delete/78332/spam Del: non-english -- https://master.php.net/note/delete/78332/non-english Del: in docs -- https://master.php.net/note/delete/78332/in+docs Del: other reasons-- https://master.php.net/note/delete/78332 Reject -- https://master.php.net/note/reject/78332 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#131195) next »