为什么此foreach循环重复两次?

时间:2018-10-22 19:11:18

标签: php php-7.2

标题中确实有问题-我有这个{ "tag": "mortgage", "app": "sneakers", "pid": 3448, "env": "production", "host": "thesaurus-mortgage", "thread": "91090300", "level": "info", "name": "Sneakers", "payload": { "class": "EgrnListenerWorker", "method": "work", "json": { "resource": "kontur", "action": "request_egrn_done", "system_code": "thesaurus", "id": 35883717, "project_id": "mortgage", "bank_id": "ab", "params": { "egrn": { "zip": "rosreestr/kontur/kontur_4288_2018-10-11_021848.zip", "pdf": "rosreestr/kontur/kontur_4288_2018-10-11_021848.pdf", "xml": "rosreestr/kontur/kontur_4288_2018-10-11_021848.xml" }, "code": "SUCCESS" } }, "valid_json": true }, "created_at": "2018-10-11T17:44:58.262+00:00" } 循环,它似乎在我的数组上迭代了两次。

foreach

我发现上面的代码在像这样传递URL时正在产生以下日志:ob_start(); $array = str_split(strtolower($_GET['text'])); foreach ($array as $char) { error_log($_GET['text'] . ', ' . sizeof($array) . ', ' . $char); } $result = ob_get_contents();

index.php?text=Hi

调试显示数组只有2个长,所以我真的不确定它可能是什么。谢谢!


经过更多调试后,我发现了以下内容:

[22-Oct-2018 20:05:37 Europe/London] Hi, 2, h
[22-Oct-2018 20:05:37 Europe/London] Hi, 2, i
[22-Oct-2018 20:05:37 Europe/London] Hi, 2, h
[22-Oct-2018 20:05:37 Europe/London] Hi, 2, i

产生这个:

if (!isset($_GET['text'])) {
    header('HTTP/1.0 404 Not Found');
    die();
}

echo uniqid() . '</br>';

//ob_start();

$total = 0;
$array = str_split(strtolower($_GET['text']));

foreach ($array as $char) {
    echo $_GET['text'] . ', ' . sizeof($array) . ', ' . $char . '</br>';
}

//$result = ob_get_contents();

echo $result;

但是取消注释两个注释行,就给了我这个:

5bce311d3d6bd
Hi, 2, h
Hi, 2, i

1 个答案:

答案 0 :(得分:0)

我想我可能还有更多关于ob_...功能的知识?

以下代码似乎是一致且可靠的:

if (!isset($_GET['text'])) {
    header('HTTP/1.0 404 Not Found');
    die();
}

echo uniqid() . '</br>';

ob_start();

$total = 0;
$array = str_split(strtolower($_GET['text']));

foreach ($array as $char) {
    echo $_GET['text'] . ', ' . sizeof($array) . ', ' . $char . '</br>';
}

ob_flush();