我有以下代码片段。

$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
// )
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top