好吧,这超出了我的想象。我必须遗漏一些明显的东西,但我找不到,是什么。
a)PHP脚本:
echo('<pre>count($connectionsData) = '.print_r(count($connectionsData), TRUE).'</pre>');
$cnt = 0;
foreach($connectionsData as $connection)
{
echo('<pre>'.(++$cnt).'. '.print_r($connection, TRUE).'</pre>');
}
b)结果:
count($connectionsData) = 1
1. 1
2. 1
3. 8
4. 1
如果可能,count
在某个变量上返回1
(一个),然后,当同一个变量放入foreach
时,那个循环实际上是四次次?
答案 0 :(得分:3)
似乎$connectionsData
是一个没有实现countable interface的对象:
class Obj{
public $var = 1;
public $var2 = 2;
}
$obj = new Obj();
echo 'count: ' . count($obj) . '<br>';
$count=0;
foreach($obj as $el){
echo ++$count . ' element: ' . $el . '<br>';
}
class CountableObj implements Countable{
public $var = 1;
public $var2 = 2;
public function count(){
return 2;
}
}
$obj = new CountableObj();
echo 'count countable: ' . count($obj) . '<br>';
$count=0;
foreach($obj as $el){
echo ++$count . ' element: ' . $el . '<br>';
}