note 43816 added to ref.array

From: Date: Mon, 05 Jul 2004 06:03:44 +0000
Subject: note 43816 added to ref.array
Groups: php.notes 
Request: Send a blank email to php-notes+get-72557@lists.php.net to get a copy of this message
I needed a function to collect a variable list, whether it is an array, a single variable, or even array with multiple sub arrays. I also needed it to collect it into a single string, that did not contain any \n characters so I could save it in a file. So the result are these two functions to compact and array, and explode it again, keeping all hierarchal information: function variables_encode($ar) { if (!is_array($ar)) { $r = rtrim(base64_encode($ar), "="); } else { foreach ($ar as $key => $value) { if ($r != '') { $r .= "&"; } $r .= rtrim(base64_encode($key), "="); $r .= "|"; $r .= rtrim(base64_encode(variables_encode($value)), "="); } } return $r; } function variables_decode($str) { if (!strstr($str,"&")) { $r = base64_decode($str); } else { $ar = explode("&",$str); foreach ($ar as $ls) { list($key,$value) = explode("|",$ls); $r[base64_decode($key)] = variables_decode(base64_decode($value)); } } return $r; } // And an example: // Create an array, with multiple sub arrays $object = "hp_contentbox.php"; $data = array("title"=>"Title","content"=>"Stuff goes here"); $objectlist[] = array("object"=>$object,"data"=>$data); $object = "hp_vspacer.php"; $objectlist[] = $object; $object = "hp_contentbox.php"; $data = array("title"=>"Profile","content"=>"User stuff"); $objectlist[] = array("object"=>$object,"data"=>$data); // Encode to string $r = variables_encode($objectlist); // Decode to array again $o2 = variables_decode($r); // Now show the user that the decoded is the same as original, and show the single string created print_r($objectlist); echo "encoded: " . $r . "\n"; print_r($o2); ---- Manual Page -- http://www.php.net/manual/en/ref.array.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+43816 Delete -- http://master.php.net/manage/user-notes.php?action=delete+43816&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+43816&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#72557) next »