Php implements the method of generating the corresponding Array Based on the string, and php string corresponds to the array
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( 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( 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
)
)
)
I hope this article will help you learn PHP programming.
How does php extract the value of an array containing a string from the array?
$ Map = array ('A' => '3, 4, 5, 6 ;',
'Bb '=> '3, 4, 6, 7 ;',
'Cc' => '5, 8, 1, 3 ;',
'Dd' => '1, 5, 7, 9 ;'
);
Foreach ($ map as $ k => $ v ){
If (strpos ($ v, '3, 4 ')! = False ){
Echo "'$ k' =>' $ V' <br/> ";
}
}
Create an Array Using strings in php
First, we need to process the string to form a php-defined array, and then execute it with eval:
$ Str ="
Array
(
[15] => Array
(
[Id] = & gt; 2304
[Fromtype] => item
)
[16] => Array
(
[Id] = & gt; 2313
[Fromtype] => item
)
[17] => Array
(
[Id] = & gt; 4265
[Fromtype] => item
)
)";
$ Str = preg_replace ('/\ [([a-z] +) \] \ s * => \ s * ([0-9a-z] + )/', "'\ $ 1' =>' \ $ 2',", $ str );
$ P = array ('array', '[', ']', ');
$ To = array ('array ',"'","'",'),');
$ Str = str_replace ($ p, $ to, $ str );
// Echo $ str;
Eval ("\ $ arr =". $ str .';');
Print_r ($ arr [15]);