foreach访问索引或关联数组

Xen*_*Yan 4 php foreach

我有以下代码片段.

$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++;
}
Run Code Online (Sandbox Code Playgroud)

预期产量:

0 is a A containing Test
1 is a B containing Test
2 is a C containing Test
3 is a D containing Test
Run Code Online (Sandbox Code Playgroud)

有没有办法省略$index变量?

Bre*_*ent 14

你的$ 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];
}

  • 实际上是索引,A,B,C和D是数组键。 (2认同)

小智 5

你可以这样做:

$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";
}
Run Code Online (Sandbox Code Playgroud)

我以前没有这样做过,但理论上它应该有效。