【问题标题】:class to load multidimensional array from a file从文件加载多维数组的类
【发布时间】:2014-06-06 17:46:00
【问题描述】:

我想创建一个从 txt 文件中读取多维数组并将 php 中检索到的数组展平的单例类。

这是我迄今为止尝试过的:

  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;
        }

txt 文件包含:

array('a', 'b', array(array('c'), 'd'), 'e', array('f'), 'g')

我用以下方式来上课:

include 'singleton.php';

$singleton = singleton::getInstance();

$flattedarray = $singleton->loadFile("file.txt");

echo '<pre>';
print_r($flattedarray);
echo'</pre>';

我得到了结果:

Array
(
    [0] => array('a', 'b', array(array('c'), 'd'), 'e', array('f'), 'g')
)

与 txt 文件中的数组相同。

不使用 eval 怎么办?

任何帮助将不胜感激

【问题讨论】:

  • 为什么要将这样的数组存储在 txt 文件中?您应该将其存储为 json 数组或序列化。

标签: php arrays oop multidimensional-array singleton


【解决方案1】:

如果你的文本文件很简单,那么你可以使用这个技巧:

$string = "array('a', 'b', array(array('c'), 'd'), 'e', array('f'), 'g')";
$string = str_replace(['array(', ')', "'"], ['[',']', '"'], $string);
var_dump(json_decode($string));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-09
    • 2017-03-10
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    相关资源
    最近更新 更多