多维数组搜索仅产生最后一级密钥

时间:2018-02-27 13:29:30

标签: php arrays laravel search multidimensional-array

我有一个搜索功能,可以在多维数组中搜索键值对。

我试图以递归方式搜索记录以获取键值匹配,如果找到匹配,我需要返回整个记录。但我的函数只返回在

中找到键值的数组

输入:

[
    {
        "_id": "5a9537b1072e100a423c2777",
        "id": "1",
        "name": "samar",
        "nick_name": "asaa",
        "address": {
            "add2": {
                "city": "BGsLR",
                "state": "Karnataka",
                "PinCode": "580d025"
            }
        },
        "updated_at": "2018-02-27 10:52:47",
        "created_at": "2018-02-27 10:49:21"
    }
.
.
.

我的功能:

public function search($key, $value)
{

    $results = array();

    $this->search_r(Contact::all()->toArray(), $key, $value, $results);
    return $results;
}

private function search_r($array, $key, $value, &$results)
{
    if (!is_array($array)) {
        return;
    }

    if (isset($array[$key]) && $array[$key] == $value) {

        $results[] = $array;
    }

    foreach ($array as $subarray) {
        $this->search_r($subarray, $key, $value, $results);
    }
}

实际输出:

   {
    "city": "BGsLR",
    "state": "Karnataka",
    "PinCode": "580d025"
   }

因为你可以看到我的函数只返回结果的最内部数组,因为我需要得到整个条目(从顶层)。

这里出了什么问题?

编辑:

预期输出:

{
    "_id": "5a9537b1072e100a423c2777",
    "id": "1",
    "name": "samar",
    "nick_name": "asaa",
    "address": {
        "add2": {
            "city": "BGsLR",
            "state": "Karnataka",
            "PinCode": "580d025"
        }
    },
    "updated_at": "2018-02-27 10:52:47",
    "created_at": "2018-02-27 10:49:21"
}

1 个答案:

答案 0 :(得分:1)

我不确定效率,但您可以使用array_filteriterators的组合:

/* I've Removed Header Data for Safety */

// Fails
$emailer['pk']['cr'] = "=====";
$emailer['pk']['cr'] .= "The message";
$emailer['pk']['cr'] .= "=====";

mail($to, $subject, $emailer['pk']['cr'], $headers);

// Works
$message = "An example message";    

mail($to, $subject, $message, $headers);

这是the demo