php如何以字符串形式表示多级数组
作者:互联网
这是php中混合的多级不规则数组的示例:
$settings['style_formats'] = array(
array('title' => 'Center table', 'selector' => 'table', 'styles' => array('margin-left' => 'auto', 'margin-right' => 'auto')),
array('title' => 'Menu style', 'selector' => 'ul,ol', 'classes' => 'menu'),
array('title' => 'Layer2', 'inline' => 'div', 'styles' => array('background-color' => 'orange')),
array('title' => 'Bold text', 'inline' => 'b'),
array('title' => 'Red text', 'inline' => 'span', 'styles' => array('color' => '#ff0000')),
array('title' => 'Red header', 'block' => 'h1', 'styles' => array('color' => '#ff0000')),
array('title' => 'Example 1', 'inline' => 'span', 'classes' => 'example1'),
array('title' => 'Example 2', 'inline' => 'span', 'classes' => 'example2'),
array('title' => 'Table styles'),
array('title' => 'Table row 1', 'selector' => 'tr', 'classes' => 'tablerow1'),
);
我需要找到一种方法来表示并将这种数组从字符串格式转换为php数组.最初的字符串格式必须是人类可以使用文本编辑器读取和写入的格式.所以例如它不应该是使用“ serialize”的结果,因为“ serialize”是一个php函数(并且不可能由人创建),并且必须可以在文本编辑器中手动创建该字符串.
该字符串将作为参数传递给一个函数,该函数会将其转换为类似上面的php数组.
如果这是一个简单的数组,我将使用逗号分隔的字符串并“爆炸”.但是它是多级的,因此使用“爆炸”将不起作用,因为它将拆分内部数组. preg_split看起来也不理想,因为该数组非常不规则.
有什么想法怎么做?
解决方法:
JSON是许多解决方案之一,例如:(原谅我不格式化)
{"style_formats":[{"title":"Center table","selector":"table","styles":{"margin-left":"auto","margin-right":"auto"}},{"title":"Menu style","selector":"ul,ol","classes":"menu"},{"title":"Layer2","inline":"div","styles":{"background-color":"orange"}},{"title":"Bold text","inline":"b"},{"title":"Red text","inline":"span","styles":{"color":"#ff0000"}},{"title":"Red header","block":"h1","styles":{"color":"#ff0000"}},{"title":"Example 1","inline":"span","classes":"example1"},{"title":"Example 2","inline":"span","classes":"example2"},{"title":"Table styles"},{"title":"Table row 1","selector":"tr","classes":"tablerow1"}]}
标签:deserialization,arrays,php 来源: https://codeday.me/bug/20191101/1983801.html