用 PHP 中更高效的东西替换嵌套的 foreach 循环
Replacing a nested foreach loop with something more efficient in PHP
我有两个数组,每个都有不同的结构:
$websites = Array (
[1131] => Array (
[httpcode] => 403
[user_id] => 265
)
[1130] => Array (
[httpcode] => 403
[user_id] => 265
)
)
$responses = Array (
[1131] => 200
[1130] => 500
)
我正在使用嵌套的 foreach 循环将 $websites
数组中的 httpcode
替换为 $responses
数组中相应的新 httpcode
:
foreach ($websites as $site_id => &$details) {
foreach ($responses as $resp_id => $new_http) {
if ($site_id == $resp_id) {
$details['httpcode'] = $new_http;
}
}
}
此操作成功,我得到了正确的结果:
$websites = Array (
[1131] => Array (
[httpcode] => 200
[user_id] => 265
)
[1130] => Array (
[httpcode] => 500
[user_id] => 265
)
)
但是,我知道嵌套的 foreach 循环在 CPU 循环中的成本很高,我想知道是否有更有效的方法对大型数组执行此操作以最小化 CPU 在服务器上使用。
第二个循环完全没有意义。这就足够了:
foreach ($websites as $site_id => &$details) {
$details['httpcode'] = $responses[$site_id];
}
如果两个数组可能不同步,您需要添加额外的密钥检查:
foreach ($websites as $site_id => &$details) {
if (array_key_exists($site_id, $responses)) {
$details['httpcode'] = $responses[$site_id];
}
}
如果数组键相同:
foreach(array_keys($websites) as $key) {
$websites[$key]['httpcode'] = $responses[$key];
}
我有两个数组,每个都有不同的结构:
$websites = Array (
[1131] => Array (
[httpcode] => 403
[user_id] => 265
)
[1130] => Array (
[httpcode] => 403
[user_id] => 265
)
)
$responses = Array (
[1131] => 200
[1130] => 500
)
我正在使用嵌套的 foreach 循环将 $websites
数组中的 httpcode
替换为 $responses
数组中相应的新 httpcode
:
foreach ($websites as $site_id => &$details) {
foreach ($responses as $resp_id => $new_http) {
if ($site_id == $resp_id) {
$details['httpcode'] = $new_http;
}
}
}
此操作成功,我得到了正确的结果:
$websites = Array (
[1131] => Array (
[httpcode] => 200
[user_id] => 265
)
[1130] => Array (
[httpcode] => 500
[user_id] => 265
)
)
但是,我知道嵌套的 foreach 循环在 CPU 循环中的成本很高,我想知道是否有更有效的方法对大型数组执行此操作以最小化 CPU 在服务器上使用。
第二个循环完全没有意义。这就足够了:
foreach ($websites as $site_id => &$details) {
$details['httpcode'] = $responses[$site_id];
}
如果两个数组可能不同步,您需要添加额外的密钥检查:
foreach ($websites as $site_id => &$details) {
if (array_key_exists($site_id, $responses)) {
$details['httpcode'] = $responses[$site_id];
}
}
如果数组键相同:
foreach(array_keys($websites) as $key) {
$websites[$key]['httpcode'] = $responses[$key];
}