本文介绍了PHP:从 foreach 循环中的数组中获取键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
print_r($samplearr) 为包含 3 个项目的数组打印以下内容:
print_r($samplearr) prints the following for my array containing 3 items:
Array ( [4722] => Array ( [value1] => 52 [value2] => 46 )
Array ( [4922] => Array ( [value1] => 22 [value2] => 47 )
Array ( [7522] => Array ( [value1] => 47 [value2] => 85 )
我想把这些放到一个 HTML 表格中,所以我做了一个 foreach 但它没有做我期望的:
I want to put these into an HTML table so I was doing a foreach but its not doing what I expected:
foreach($samplearr as $item){
print "<tr><td>" . key($item) . "</td><td>" . $samplearr['value1'] . "</td><td>" . $samplearr['value2'] . "</td></tr>";
}
返回的是:
<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>
我需要使用什么函数来代替 key($item) 来获取 4722?
What function do I need to be using instead of key($item) to get the 4722?
推荐答案
试试这个:
foreach($samplearr as $key => $item){
print "<tr><td>"
. $key
. "</td><td>"
. $item['value1']
. "</td><td>"
. $item['value2']
. "</td></tr>";
}
这篇关于PHP:从 foreach 循环中的数组中获取键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!