PHP:在foreach循环中获取数组中的键
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 )
我想把这些放到一个HTML表格中,所以我做了一个foreach,但是没有按照我的预期做:
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>
这将是我想要的第一个输出:
<tr><td>4722</td><td>52</td><td>46</td></tr>
我需要使用什么函数来代替键($ item)来获得4722?
尝试这个:
foreach($samplearr as $key => $item){ print "<tr><td>" . $key . "</td><td>" . $item['value1'] . "</td><td>" . $item['value2'] . "</td></tr>"; }
使用键和值的foreach 。
例:
foreach($samplearr as $key => $val) { print "<tr><td>" . $key . "</td><td>" . $val['value1'] . "</td><td>" . $val['value2'] . "</td></tr>"; }
你需要嵌套的foreach循环
foreach($samplearr as $key => $item){ echo $key; foreach($item as $detail){ echo $detail['value1'] . " " . $detail['value2'] } }
foreach($samplearr as $item) { print "<tr><td>" . array_keys($item) . "</td><td>" . $samplearr['value1'] . "</td><td>" . $samplearr['value2'] . "</td></tr>"; }
用array_keys
改变你的关键函数。