【问题标题】:output specific array key for each result为每个结果输出特定的数组键
【发布时间】:2012-05-04 22:26:37
【问题描述】:

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

所以我有这个代码:

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

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

【问题讨论】:

  • 到有计数器的部分:必须是++$counter;或 $counter++;
  • 你的数组的结构是什么?

标签: php mysql arrays for-loop foreach


【解决方案1】:
foreach ($results as $key => $result) {
  echo 'this is result: ' . $key;
}

当前的key 将分配给$key,该属性的value 将分配给$result

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

编辑

作为对您的 cmets 的回应,我认为这就是您想要实现的目标:-

$i=0;
foreach($results as $result) {
  echo 'this is result: ' . ++$i;
}

【讨论】:

  • 这很好用。我还想知道一件事。如何将开始设置为 1 而不是 0?非常感谢。
  • 您可以使用continue 跳过数组的第一次迭代,我将编辑我的答案
  • 还有别的办法吗?第一个数组 [0] 包含输入。如果使用该输入将不会显示。
  • 抱歉,我错误地认为您有一个数字索引数组,不太确定为什么,因为它没有意义。我已经更新了我的答案。
  • 我也犯了同样的错误。似乎 continue 很容易跳转到该数组中的下一个条目。所以第一个不会被考虑。
【解决方案2】:
foreach($arr as $key=>$val){
//do something with key and value
}

【讨论】:

    【解决方案3】:

    在代码中你可以先检查$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*/
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-11
      • 2016-03-22
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多