문제

다음 코드 조각이 있습니다.

$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