使用while循环PHP填充数组
我想使用while循环填充数组。使用下面的代码,我只得到一行数据。但如果我打印$count,它的最终值是432。有什么想法吗?我已经试了好几天了,但还是想不出来使用while循环PHP填充数组,php,arrays,while-loop,Php,Arrays,While Loop,我想使用while循环填充数组。使用下面的代码,我只得到一行数据。但如果我打印$count,它的最终值是432。有什么想法吗?我已经试了好几天了,但还是想不出来 // Populate objects array $count = 1; while($o_result->nextHit()) { $t_object = new ca_objects($o_result->get('ca_objects.object_id')); $o_c_date = $t_ob
// Populate objects array
$count = 1;
while($o_result->nextHit()) {
$t_object = new ca_objects($o_result->get('ca_objects.object_id'));
$o_c_date = $t_object->getCreationTimestamp();
$o_lm_date = $t_object->getLastChangeTimestamp();
$a_objects = array ( array (
'title' => $o_result->get('ca_objects.preferred_labels.name'),
'type' => $o_result->get('ca_objects.type_id',array(
'convertCodesToDisplayText' => true))
)
);
$count++;
}
//print results
foreach ($a_objects as $row) {
echo $row['title']."<br/>";
echo $row['type']."<br/>";
}
echo $count."<br/>\n" ; //This prints 432
//填充对象数组
$count=1;
而($o_result->nextHit()){
$t_object=新的ca_对象($o_result->get('ca_objects.object_id'));
$o_c_date=$t_object->getCreationTimestamp();
$o_lm_date=$t_object->getLastChangeTimestamp();
$a_objects=数组(数组(
'title'=>$o_result->get('ca_objects.preferred_labels.name'),
'type'=>$o\u result->get('ca\u objects.type\u id',数组(
'convertCodesToDisplayText'=>true))
)
);
$count++;
}
//打印结果
foreach($a_对象作为$row){
echo$row['title']。“
”;
echo$row['type']。“
”;
}
回显$count。“
\n”//这张是432
每次迭代都要重置数组$a_对象
,而不是附加到数组中
改为这样做:
// outside the loop:
$a_objects = array();
// inside the loop:
$a_objects[] = array (
'title' => $o_result->get('ca_objects.preferred_labels.name'),
'type' => $o_result->get(
'ca_objects.type_id',
array('convertCodesToDisplayText' => true)
)
)
);
我还在
标题
和类型
键周围加上引号,您也应该这样做——如果不使用引号,PHP会尝试猜测您的意思,但这是一种不好的做法,你应该停止使用它。你在每个循环中都声明了你的数组。如果你甚至不知道数组是什么,你怎么能编写这样的while循环?谢谢你的回答,我正在学习。非常感谢你,作为php新手,我往往会犯新手错误。我会尽快接受你的回答。@sscarano:很乐意帮忙。还要确保你现在就读这本书,这会为你将来省去很多麻烦。PHP的特性也是如此。再次感谢。我将阅读教程,我正在阅读一本关于php的书,但有时我看不到简单的错误。