1

我的页面有一个搜索引擎。因此,我想为每个结果输出数组键。

所以我有这个代码:

$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;
    }
}

什么不像我想的那样工作,仍然不是那么专业。所以如果有人能告诉我如何解决这个问题,我真的很感激。多谢。

4

3 回答 3

2
foreach ($results as $key => $result) {
  echo 'this is result: ' . $key;
}

currentkey将被分配给该属性,$key并且value该属性将被分配给$result

http://php.net/manual/en/control-structures.foreach.php

编辑

针对您的评论,我认为这就是您想要实现的目标:-

$i=0;
foreach($results as $result) {
  echo 'this is result: ' . ++$i;
}
于 2012-04-24T09:40:03.567 回答
1
foreach($arr as $key=>$val){
//do something with key and value
}
于 2012-04-24T09:40:14.037 回答
0

Here in code you can check first if $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*/
 }
}
于 2012-04-24T10:44:21.647 回答