note 101211 added to function.array-walk

From: Date: Thu, 02 Dec 2010 11:20:37 +0000
Subject: note 101211 added to function.array-walk
Groups: php.notes 
Request: Send a blank email to php-notes+get-174557@lists.php.net to get a copy of this message
Prefix array values with keys and retrieve as a glued string, the original array remains unchanged. I used this to create some SQL queries from arrays. <?php function array_implode_prefix($outer_glue, $arr, $inner_glue, $prefix=false){ array_walk( $arr , "prefix", array($inner_glue, $prefix) ); return implode($outer_glue, $arr); } function prefix(&$value, $key, array $additional){ $inner_glue = $additional[0]; $prefix = isset($additional[1])? $additional[1] : false; if($prefix === false) $prefix = $key; $value = $prefix.$inner_glue.$value; } //Example 1: $order_by = array("3"=>"ASC", "2"=>"DESC", "7"=>"ASC"); echo array_implode_prefix(",", $order_by, " "); //Output: 3 ASC,2 DESC,7 ASC //Example 2: $columns = array("product_id", "category_id", "name", "description"); $table = "product"; echo array_implode_prefix(", ", $columns, ".", $table); //Output:product.product_id, product.category_id, product.name, product.description //Example 3 (function prefix) won't really be used on its own $pre= "vacation"; $value = "lalaland"; prefix($value, $pre, array(".")); echo $value; //Output: vacation.lalaland ?> ---- Server IP: 69.147.83.197 Probable Submitter: 196.210.162.30 ---- Manual Page -- http://www.php.net/manual/en/function.array-walk.php Edit -- https://master.php.net/note/edit/101211 Del: integrated -- https://master.php.net/note/delete/101211/integrated Del: useless -- https://master.php.net/note/delete/101211/useless Del: bad code -- https://master.php.net/note/delete/101211/bad+code Del: spam -- https://master.php.net/note/delete/101211/spam Del: non-english -- https://master.php.net/note/delete/101211/non-english Del: in docs -- https://master.php.net/note/delete/101211/in+docs Del: other reasons-- https://master.php.net/note/delete/101211 Reject -- https://master.php.net/note/reject/101211 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#174557) next »