Home > Backend Development > PHP Tutorial > 多维数组循环读取有关问题

多维数组循环读取有关问题

WBOY
Release: 2016-06-13 13:10:23
Original
806 people have browsed it

多维数组循环读取问题
多维数组
array(
  'a'=>array(
  'a2'=>array('dd','ff','gg'),
  'a3'=>array('dd','ff','gg')
  ),
  'b'=>array(
  'b2'=>array('22','55','88'),
  'b3'=>array(
  'cs'=>array('nn','mm','xx')
  )
  )
)

字符串
a.a2
b.b2
b.b3.cs

如何根据这个字符串读取相应的数组?

比如
a.a2 = ['a']['a2'] 结果是 array('dd','ff','gg')
b.b2 = ['b']['b2'] 结果是 array('22','55','88')
b.b3.cs = ['b']['b3']['cs'] 结果是 array('nn','mm','xx')


注:数组深度不限,最好不要遍历,绝对不能用eval

顺便问一下eval除了安全问题,效率是不是挺差的?

------解决方案--------------------

PHP code
$ar = array(
  'a'=>array(
  'a2'=>array('dd','ff','gg'),
  'a3'=>array('dd','ff','gg')
  ),
  'b'=>array(
  'b2'=>array('22','55','88'),
  'b3'=>array(
  'cs'=>array('nn','mm','xx')
  )
  )
);
$s = 'b.b3.cs';
$p =& $ar;
foreach(explode('.', $s) as $k) {
  if(isset($p[$k])) $p = $p[$k];
}
print_r($p);
<br><font color="#e78608">------解决方案--------------------</font><br>
Copy after login
PHP code
$ar = array(
  'a'=>array(
     'a2'=>array('dd','ff','gg'),
      'a3'=>array('dd','ff','gg')
  ),
  'b'=>array(
     'b2'=>array('22','55','88'),
     'b3'=>array(
         'cs'=>array('nn','mm','xx')
      )
  )
);
$s = 'b.b3.cs';
$s = explode('.', $s);
$p =& $ar;
For($i=0;$i<count if print_r></count><font color="#e78608">------解决方案--------------------</font><br>既然 绝对不能用eval<br>还要 不要遍历<br>那么你打算如何识别被 “.” 分隔的这些键值呢?
<br><font color="#e78608">------解决方案--------------------</font><br>你如果想要不用foreach,如果不考虑效率问题可以自己写个函数递归取值,不过递归函数在php里效率低的可怕 <div class="clear">
                 
              
              
        
            </div>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template