You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RecursiveIteratorIterator忽略值为数组的键,如何实现按键搜索数组值?

数组按键搜索:值为数组时的匹配问题

我想要通过键搜索数组中的值,但当目标键对应的取值为数组时遇到了问题,以下是我的代码:

$key_to_search = "sizes";
$result   = [];
$array =  [
    "color" => "red",
    "subcolor" => "green",
    "sizes" => [
        "depth_mm" => 40.5,
        "width_mm" => 300,
        "height_mm" => 2
    ],
    "launch_date" => "2023-01-01"
];

$iterator = new \RecursiveIteratorIterator(
    new \RecursiveArrayIterator(
        $array
    )
); 

foreach($iterator as $key=>$value)
{
   if($key_to_search==$key && $value!=='')
   {
      $result[] = $value;
   }
}

var_dump($result);

待搜索的键存储在$key_to_search变量中,若目标键对应的取值不是数组,代码能正确找到对应值;但当取值为数组时,该键会被忽略。

搜索"sizes"的预期结果为:

[
   "depth_mm" => 40.5,
   "width_mm" => 300,
   "height_mm" => 2
]

以下是不使用RecursiveIteratorIterator的传统递归实现方式,可正常工作:

public function searchPropertyValuesByKey($key_to_search, $array_to_search = null) {
    if($array_to_search == null) {
       $array_to_search = [
        "color" => "red",
        "subcolor" => "green",
        "sizes" => [
            "depth_mm" => 40.5,
            "width_mm" => 300,
            "height_mm" => 2
        ],
        "launch_date" => "2023-01-01"
      ];
    }

    $result = [];
    foreach($array_to_search as $key=>$value)
    {
        if($key_to_search==$key && $value!=='')
        {
            $result[] = $value;
        }
        if(is_array($value)){
            $callback_result = $this->searchPropertyValuesByKey($key_to_search, $value);
            if($callback_result !== null) {
                $result[] = $callback_result;
            }
        }
    }
    if(count($result) == 1)
        return $result[0];
    else if(count($result) > 1)
        throw new \Exception("Property '" . $key_to_search . "' is found multiple times! (" . count($result) . ") " . json_encode($result) . ", in product_id: " . $this->id . " >> " . json_encode($this->propierties) . "");
    else
        return null;
}

内容的提问来源于stack exchange,提问作者Troyer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 06:27:32