退货不起作用,但打印有效

时间:2018-07-04 12:52:58

标签: php

我正在尝试在多维数组中搜索并获取值,但返回不起作用。

function search($arr,$q){
  foreach($arr as $key => $val){
    if(trim($key) == $q) return $arr;
    else if(is_array($val))  search($val,$q);
  }
}

但是回显和打印工作。

问题出在哪里?

1 个答案:

答案 0 :(得分:0)

不确定您已经解决了此问题,但这是一种可能会帮助您的解决方案:

<?php
$arr = ['firstname' => 'John', 'lastname' => 'Dough', 'jobs' => ['job1' => 'writer', 'job2' => 'dad']];

$result = null; // the container for the search result
$key = 'job1'; // the key we are looking for
findKey($arr, $key, $result); // invoke the search function

/** print the result of our search - if key not found, outputs 'NULL' */
echo '<pre>';
var_dump($result); // output: string(6) "writer"
echo '<pre>';

/**
 * @param array $arr        the multidimensional array we are searching
 * @param string $key       the key we are looking for
 * @param $result           passed by reference - in case the key is found, this variable 'stores' the corresponding value.
 */
function findKey($arr = [], $key = '', &$result)
{
    foreach ($arr as $key0 => $value0) {
        if($key0 == $key) {
            $result = $value0;
        }
        if(is_array($value0)) {
            findKey($value0, $key, $result);
        }
    }
    return false;
}