我有以下代码片段.
$items['A'] = "Test"; $items['B'] = "Test"; $items['C'] = "Test"; $items['D'] = "Test"; $index = 0; foreach($items as $key => $value) { echo "$index is a $key containing $value\n"; $index++; }
预期产量:
0 is a A containing Test 1 is a B containing Test 2 is a C containing Test 3 is a D containing Test
有没有办法省略$index
变量?
你的$ index变量有点误导.这个数字不是索引,你的"A","B","C","D"键都是.您仍然可以通过编号索引$ index [1]访问数据,但这不是重点.如果你真的想保留编号索引,我几乎要重组数据:
$items[] = array("A", "Test"); $items[] = array("B", "Test"); $items[] = array("C", "Test"); $items[] = array("D", "Test"); foreach($items as $key => $value) { echo $key.' is a '.$value[0].' containing '.$value[1]; }