内部 foreach 始终具有外部 foreach 的最后一次迭代


Inner foreach always has last iteration of outer foreach

我有以下foreach循环(带有内部foreach循环):

foreach ($options_default as $key=>$value) {
        foreach ($option_names as $option_name_key=>$option_name_value){
            $temp = array($key=>$value);
            update_option($option_name_value, $temp);
            unset($temp);   
        }
    }

此循环遍历这两个数组:

    $option_names = array (
                'API_URL'=>'api-url',
                'API_CDN_URL'=>'cdn-url',
                'API_USERNAME'=> 'api-username'
    );
    $options_default = array (
            'api_url' => 'url1', 
            'cdn_url' => 'url2', 
            'api_username' => 'test', 
);

但是,$temp的值始终设置为 $options_default 数组中的最后一个键/值对。谁能建议这里的问题可能是什么?

->预期产量

因此,循环将调用这三个更新选项(假设我只是传递$value作为第二个参数以方便):

update_option(api-url,url1);
update_option(cdn-url,url2);
update_option(api-username,test);

再想想你的foreach循环结构,以及为什么它没有做你想要的。您当前在 $option_names 上循环了 3 次,这导致对 update_option 的 9 次调用。也看看update_option的参数。在代码中,要向其传递两个参数:字符串和数组。但你显然想要的是两根绳子。

您可以将 MultipleIterator 与 ArrayIterator 结合使用来完成此任务:

$iterator = new MultipleIterator();
$iterator->attachIterator(new ArrayIterator($option_names));
$iterator->attachIterator(new ArrayIterator($options_default));
foreach ($iterator as $values) {
    update_option($values[0], $values[1]);
}

希望这有帮助