foreach访问索引或者关联数组
时间:2020-03-05 18:54:57 来源:igfitidea点击:
我有以下代码片段。
$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]; }
回答
你可以这样做:
$items[A] = "Test"; $items[B] = "Test"; $items[C] = "Test"; $items[D] = "Test"; for($i=0;$i<count($items);$i++) { list($key,$value) = each($items[$i]); echo "$i $key contains $value"; }
我以前没有做过,但是从理论上讲应该可以。
回答
请注意在此处定义键的方式。虽然示例有效,但可能并非总是如此:
$myArr = array(); $myArr[A] = "a"; // "A" is assumed. echo $myArr['A']; // "a" - this is expected. define ('A', 'aye'); $myArr2 = array(); $myArr2[A] = "a"; // A is a constant echo $myArr['A']; // error, no key. print_r($myArr); // Array // ( // [aye] => a // )