带有 CachingIterator 的 PHP 数组到字符串转换通知

Lit*_*ode 2 php spl

我已经在 Stackoverflow 上对这个主题进行了一些搜索,但是据我所知,我没有将数组视为字符串?

我收到的消息是:

第 42 行 X 中的数组到字符串转换

我的代码的第 42 行是一个foreach循环的开始:

foreach ($collection as $element) {
Run Code Online (Sandbox Code Playgroud)

Variable$collection是一个基于数据库输出的缓存迭代器:

$collection=new \CachingIterator(new \ArrayIterator($this->dbData));

如果我print_r()打开$this->dbData,我肯定会得到一个数组:

Array
(
    [0] => Array
        (
            [c_id] => A
 )

    [1] => Array
        (
            [c_id] => B
)
Run Code Online (Sandbox Code Playgroud)

所以,总结一下:

  • 我们有一个数组的确认输出
  • 我们知道ArrayIterator()期望一个arrayas 参数
  • 我们知道CachingIterator()期望一个Iteratoras 参数
  • 我们知道foreach()可以循环Iterator

TL;DR我真的不确定我在这里将什么视为字符串?

编辑添加....

即使我大大简化了我的代码,我仍然可以重现:

<?php
error_reporting (E_ALL | E_STRICT);
ini_set ('display_errors', 1);
$arrX=array(array("c_id"=>"A"),array("c_id"=>"B"));
$collection=new \CachingIterator(new \ArrayIterator($arrX));
foreach($collection as $element) {
echo $element["c_id"].PHP_EOL;
}
Run Code Online (Sandbox Code Playgroud)

注意:第 6 行 /Users/bp/tmp/test.php 中的数组到字符串转换

一种

注意:第 6 行 /Users/bp/tmp/test.php 中的数组到字符串转换

sal*_*the 5

简短的回答是,您无意中要求CachingIterator在迭代期间将子数组转换为字符串。CachingIterator::CALL_TOSTRING要不这样做,请不要使用或CachingIterator::TOSTRING_USE_INNER标志。

您可以不设置任何标志,通过使用0作为$flags参数的值,或使用不同的标志:这可以在构造函数中完成,或者在初始化之后使用CachingIterator::setFlags().

例如:

$array = [["c_id" => "A"], ["c_id" => "B"]];
$collection = new CachingIterator(new ArrayIterator($array), 0);
foreach ($collection as $element) {
    // no E_NOTICE messages, yay!
}
Run Code Online (Sandbox Code Playgroud)

还有几句话作为解释......

默认情况下,CachingIterator该类CachingIterator::CALL_TOSTRING按照PHP 手册页CachingIterator中的说明设置标志。

public __construct ( Iterator $iterator [, int $flags = self::CALL_TOSTRING ] )
Run Code Online (Sandbox Code Playgroud)

当设置此标志(或CachingIterator::TOSTRING_USE_INNER标志)并且CachingIterator::next()调用该方法(即在迭代期间)时,当前值(在本例中为每个子数组)或内部迭代器(在本例中为ArrayIterator)分别转换为一个字符串并在内部保存。此字符串值CachingIterator::__toString()是使用这些标志之一时返回的值。

使用任何其他标志时,调用CachingIterator::next().