This article mainly introduces the php method for generating corresponding arrays based on strings, including array operation techniques and eval function usage. For more information, see
This article mainly introduces the php method for generating corresponding arrays based on strings, including array operation techniques and eval function usage. For more information, see
This example describes how to generate an Array Based on strings in php. It is a practical technique. Share it with you for your reference. The specific method is as follows:
Take a look at the following example:
<? Php $ config = array ('Project | page | Index' => 'content', 'Project | page | nav '=> array ('image' => '1.jpg ', 'name' => 'home'), array ('image' => '2.jpg ', 'name' => 'about ')), 'Project | page | open' => true);?>
Generate the following Array Based on $ config:
<? Php $ result = array ('project' => array ('page' => array ('index' => 'content ', 'nav' => array ('image' => '1.jpg ', 'name' => 'home'), array ('image' => '2.jpg ', 'name' => 'about'), 'open' => true);?>
Method: Use eval to implement:
<? Php $ config = array ('Project | page | Index' => 'content', 'Project | page | nav '=> array ('image' => '1.jpg ', 'name' => 'home'), array ('image' => '2.jpg ', 'name' => 'about ')), 'Project | page | open' => true); $ result = array (); foreach ($ config as $ key => $ val) {$ tmp = ''; $ keys = explode ('|', $ key); for ($ I = 0, $ len = count ($ keys); $ I <$ len; $ I ++) {$ tmp. = "['". $ keys [$ I]. "']";} if (is_array ($ val) {eval (' $ Result '. $ tmp. '= '. var_export ($ val, true ). ';');} elseif (is_string ($ val) {eval ('$ result '. $ tmp. '= '. $ val. ';');} else {eval ('$ result '. $ tmp. '= $ val;') ;}} print_r ($ result);?>
Output result:
Array
(
[Project] => Array
(
[Page] => Array
(
[Index] => content
[Nav] => Array
(
[0] => Array
(
[Image] => 1.jpg
[Name] => home
)
[1] => Array
(
[Image] => 2.jpg
[Name] => about
)
)
[Open] => 1
)
)
)
I hope this article will help you learn PHP programming.