Home > Article > Backend Development > How to generate corresponding array based on string through php
php generates the corresponding array method based on the string
For example:
<?php $config = array( 'project|page|index' => 'content', 'project|page|nav' => array( array( 'image' => '1.jpg', 'name' => 'home' ), array( 'image' => '2.jpg', 'name' => 'about' ) ), 'project|page|open' => true ); ?>
Generate the following array according to $config
<?php $result = array( 'project' => array( 'page' => array( 'index' => 'content', 'nav' => array( 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( 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 ) ) )
This article explains how to generate corresponding arrays based on strings through PHP. For more related content, please pay attention to the PHP Chinese website.
Related recommendations:
Explanation on the solution to the lack of double quotes in the JSON string key
How Obtain https request method through curl
Explanation on uploading pictures and saving them to the database through php
The above is the detailed content of How to generate corresponding array based on string through php. For more information, please follow other related articles on the PHP Chinese website!