Problem with returning value from a recursive method in PHP

WBOY
Release: 2016-10-20 10:08:52
Original
870 people have browsed it
<code><?php
$array = array(
    0 => array(
      '1a' => '',
      '3a' => '',
      '6a' => array(
        '6a1' => '',
        '6a2' => '',
        '6a3' => array(
          '6a31' => '',
          '6a33' => '',
          '6a34' => '1',
          ),
        ),
      ),
    1 => array(
      '3b' => '',
      '4b' => array(
        '4b1' => '',
        '4b2' => '',
        ),
      '6b' => '',
      )
    );

function search_val($key, $arr) {
  $v = '';
  foreach ($arr as $ks => $vs) {
    if($ks != $key && is_array($vs)) {
      search_val($key, $vs);
    }else if($ks != $key && is_string($vs)) {
      continue;
    }else if($ks == $key) {
      $v = $vs;
      break;
    }
  }
  return $v; 
  //var_dump($v);exit; //这里是有值的 为1
  //echo $v;  //测试这样可以直接输出
}
$va = search_val('6a34', $array);
var_dump($va); //$va始终为空 
</code>
Copy after login

The meaning of this method is to get the value corresponding to val for the subscript $key. I return $v at the end of the method, and then I assign the result of this return to a value $va, this The value is always empty, but when I print $v at the end of the method, it has a value. Why is this? Is it a problem with variable scope or is it caused by irregularities in my code? Solve

Related labels:
php
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