foreach访问索引或关联数组

时间:2008-09-16 01:35:08

标签: 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++;
}

预期产出:

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变量?

3 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分:4)

你可以这样做:

$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";
}

我之前没有这样做,但理论上它应该有用。

答案 2 :(得分:1)

小心你在那里如何定义你的钥匙。虽然您的示例有效,但可能并非总是如此:

$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
// )