5

次のコード スニペットがあります。

$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変数を除外する方法はありますか?

4

3 に答える 3

15

あなたの $index 変数は誤解を招くようなものです。その番号はインデックスではなく、「A」、「B」、「C」、「D」キーです。番号付きインデックス $index[1] を介してデータにアクセスすることはできますが、それは重要ではありません。番号付きインデックスを本当に保持したい場合は、データをほとんど再構築します。

$items[] = array("A", "テスト");
$items[] = array("B", "テスト");
$items[] = array("C", "テスト");
$items[] = array("D", "Test");

foreach($items as $key => $value) {
    $key をエコーし​​ます。「.$value[0].」です。'.$value[1]; を含む
}
于 2008-09-16T01:41:00.467 に答える
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";
}

私は以前にそれをやったことがありませんが、理論的にはうまくいくはずです。

于 2008-09-16T01:47:09.157 に答える
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
// )
于 2008-09-16T02:32:29.390 に答える