PHP:从 foreach 循环中的数组中获取键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10992005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:32:52  来源:igfitidea点击:

PHP: Get the key from an array in a foreach loop

phparraysforeach

提问by SystemX17

print_r($samplearr) prints the following for my array containing 3 items:

print_r($samplearr) 为包含 3 个项目的数组打印以下内容:

Array ( [4722] => Array ( [value1] => 52 [value2] => 46 )
Array ( [4922] => Array ( [value1] => 22 [value2] => 47 )
Array ( [7522] => Array ( [value1] => 47 [value2] => 85 )

I want to put these into an HTML table so I was doing a foreach but its not doing what I expected:

我想将这些放入一个 HTML 表中,所以我在做一个 foreach 但它没有做我期望的:

foreach($samplearr as $item){
     print "<tr><td>" . key($item) . "</td><td>" . $samplearr['value1'] . "</td><td>" . $samplearr['value2'] . "</td></tr>";
}

Which is returning:

这是返回:

<tr><td>value1</td><td>52</td><td>46</td></tr>

This would be the first output I am wanting:

这将是我想要的第一个输出:

<tr><td>4722</td><td>52</td><td>46</td></tr>

What function do I need to be using instead of key($item) to get the 4722?

我需要使用什么函数而不是 key($item) 来获取 4722?

回答by flowfree

Try this:

尝试这个:

foreach($samplearr as $key => $item){
  print "<tr><td>" 
      . $key 
      . "</td><td>"  
      . $item['value1'] 
      . "</td><td>" 
      . $item['value2'] 
      . "</td></tr>";
}

回答by Haim Evgi

Use foreachwith key and value.

foreach与键和值一起使用。

Example:

例子:

foreach($samplearr as $key => $val) {
     print "<tr><td>" 
         . $key 
         . "</td><td>" 
         . $val['value1'] 
         . "</td><td>" 
         . $val['value2'] 
         . "</td></tr>";
}

回答by David Stetler

you need nested foreach loops

你需要嵌套的 foreach 循环

foreach($samplearr as $key => $item){
   echo $key;
    foreach($item as $detail){
       echo $detail['value1'] . " " . $detail['value2']
     }
 }