php RecursiveIteratorIterator忽略数组键

thigvfpy  于 2023-03-16  发布在  PHP
关注(0)|答案(1)|浏览(88)

我想按键搜索数组中的值,但当这些键值是数组时,我遇到了麻烦,我有以下代码:

$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变量,如果我使用另一个没有数组作为值的变量,它会正确找到值,但当值是数组时,它会忽略。
检索“尺寸”的预期结果为:

[
   "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;
}
k4emjkb1

k4emjkb11#

如果您将$iterator的定义更改为以下内容,它将按您所述的方式工作:

$iterator = new \RecursiveArrayIterator($data);

我认为不需要RecursiveIteratorIterator

相关问题