我的页面有搜索引擎。因此,我想为每个结果输出数组键。
所以我有这段代码:
$results = search($keywords);
$results_num = count($results); //what shows the message how many items were found
if (!empty($errors){
foreach ($results as $result){
echo "this is result: "
.$result['key']; //thought would be the solution, its not.
}
} else {
foreach ($errors as $error){
$error;
}
}
我也试过使用像:
这样的计数器$results = search($keywords);
$results_num = count($results); //what shows the message how many items were found
$counter = 0;
if (!empty($errors){
foreach ($results as $result){
$counter++;
echo "this is result: "
.$counter;
}
} else {
foreach ($errors as $error){
$error;
}
}
什么不起作用,因为我认为,仍然不是那么专业。 所以,如果有人能告诉我如何解决这个问题,我真的很感激。非常感谢。
答案 0 :(得分:2)
foreach ($results as $key => $result) {
echo 'this is result: ' . $key;
}
当前key
将分配给$key
,该属性的value
将分配给$result
http://php.net/manual/en/control-structures.foreach.php
修改强>
在回应您的评论时,我认为这是您要实现的目标: -
$i=0;
foreach($results as $result) {
echo 'this is result: ' . ++$i;
}
答案 1 :(得分:1)
foreach($arr as $key=>$val){
//do something with key and value
}
答案 2 :(得分:0)
在代码中,您可以先检查$results array is not empty because sometime due to empty $results array foreach generates error
/*Check if $results array is empty or not*/
if(!empty($results)){
foreach ($results as $key=>$result){
/*result you want to show here according conditions*/
}
}