note 97588 deleted from function.implode by danbrown

From: Date: Tue, 27 Apr 2010 14:29:07 +0000
Subject: note 97588 deleted from function.implode by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-168721@lists.php.net to get a copy of this message
Note Submitter: Sasan ---- What we need is a formatted implode function for multi-dimensional arrays. this function would remove the need for a lot of functions described in comments below. So here it is (implementation included): Function Prototype: --------------------- function fimplode($fmt, $glue, $arr); Arguments: fmt: a format string (ala fprint()) where for each array item in a hierarchical array the following keys in the string are replaced with the following: "%k" replaced with key for array item '%p" replaced with hierarchical path for an array item This is the empty string if array item is at level 1 Example path can be: "[0][1][A]" for a 4 deep array item. "%v" replaced with value for array item glue: glue string between array elements arr : the array which may be hierarchical Examples: single-dimension array: --------------------------------- $arr = array(100,'A'=>101,102,103,104); -To get a comma-separated list of all keys: echo fimplode("%k", ", ", $arr); 0, A, 1, 2, 3 -To get a comma-separated list of all values: echo fimplode("%v", ", ", $arr); 100, 101, 102, 103, 104 -To get a string you can use in an SQL: echo fimplode("%k='%v'", " and ", $arr); 0='100' and A='101' and 1='102' and 2='103' and 3='104' Example for multi-dimension array: ---------------------------------- $arr = array(100,'A'=>101,102,array(201,array(301,302,303),203),104); -To get a list of all paths: echo fimplode("'%p'", ", ", $arr); '', '', '', '[2]', '[2][1]', '[2][1]', '[2][1]', '[2]', '' -To get a list of all full keys: echo fimplode("'%p[%k]'", ", ", $arr); '[0]', '[A]', '[1]', '[2][0]', '[2][1][0]', '[2][1][1]', '[2][1][2]', '[2][2]', '[3]' -To get php code you can use to recreate the array: echo fimplode("\$arr%p[%k]='%v';", "\n", $arr); $arr[0]='100'; $arr[A]='101'; $arr[1]='102'; $arr[2][0]='201'; $arr[2][1][0]='301'; $arr[2][1][1]='302'; $arr[2][1][2]='303'; $arr[2][2]='203'; $arr[3]='104'; Implementation: ------------------ <? function fimplode_private_reformat(&$item, $key, $args) { $fmt = str_replace("%p", (is_array($item)?"[".$key."]%p":""), $args[0]); if( is_array($item)) $item=fimplode($fmt, $args[1], $item); else $item=str_replace("%v", $item, str_replace("%k", $key, $fmt)); } function fimplode($fmt="%v", $glue="", $arr) { array_walk($arr, 'fimplode_private_reformat', array($fmt, $glue)); return implode($glue, $arr); } ?>

« previous php.notes (#168721) next »