user12345 Posted June 6, 2014 Share Posted June 6, 2014 (edited) I want to create a singleton class that read multidimensional array from txt file and flatten the array retrieved. This is what I have tried so far: class singleton { protected static $instance = null; public static function getInstance() { if (!isset(static::$instance)) { static::$instance = new static; } return static::$instance; } public static function flattenArray($array) { $return = array(); $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array)); foreach ($iterator as $value) { $return[] = $value; } return $return; } public static function loadFile($path) { $file_handle = fopen($path, "r"); while (!feof($file_handle)) { $line = fgets($file_handle); $rawarray[] = $line; } $flattedarray = self::flattenArray($rawarray); fclose($file_handle); return $flattedarray; } With the txt file containing: array('a', 'b', array(array('c'), 'd'), 'e', array('f'), 'g') I run the class with: include 'singleton.php'; $singleton = singleton::getInstance(); $flattedarray = $singleton->loadFile("file.txt"); echo '<pre>'; print_r($flattedarray); echo'</pre>'; I get as a result: Array ( [0] => array('a', 'b', array(array('c'), 'd'), 'e', array('f'), 'g') ) Which is the same array found in the txt file. how can i do it without using eval. What am I doing wrong ? Edited June 6, 2014 by Maq Quote Link to comment Share on other sites More sharing options...
Solution Ch0cu3r Posted June 6, 2014 Solution Share Posted June 6, 2014 PHP will not read the text file as PHP code. It will see it as just plain text. If you need to save an array to a flat file, you should either serialise it or json_encode it. You then use unserialize or json_decode to read the array back into PHPs memory. Quote Link to comment Share on other sites More sharing options...
Maq Posted June 6, 2014 Share Posted June 6, 2014 @OP, please use code tags when posting code. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.