質問

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

$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