Domanda

Ho il seguente frammento di codice.

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

Uscita prevista:

0 is a A containing Test
1 is a B containing Test
2 is a C containing Test
3 is a D containing Test

C'è un modo per lasciare il $index variabile?

È stato utile?

Soluzione

Il tuo $indice variabile tipo di ingannevole.Quel numero non è l'indice, la "A", "B", "C", "D" tasti sono.È ancora possibile accedere ai dati attraverso i numeri indice $index[1], ma che in realtà non è questo il punto.Se si vuole veramente per mantenere l'indice numerazione, avevo quasi ristrutturare i dati:

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

Altri suggerimenti

Si può fare questo:

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

Non ho fatto prima, ma in teoria dovrebbe funzionare.

Essere attenti a come si sta definendo le vostre chiavi.Mentre il tuo esempio funziona, non sempre può:

$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
// )
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top