2010-09-14 10 views
0

J'espère que vous allez bien. Ma question:PHP Array question?

En MYSQL j'ai une table avec ce type de champ

Nom du champ: TAGS Valeur: xavier, celine, Marise, leon, john, cathy, Polux, Maurice


en PHP je fais ce

$xwords = array(); 
function array_rpush(&$arr, $item) 
{ 
    $arr = array_pad($arr, -(count($arr) + 1), $item); 
} 

$tags = requete("SELECT tags FROM tbl_tags LIMIT 1;"); 
while($dtags = mysql_fetch_assoc($tags)){ 
    $words .= array_rpush($xwords, $dtags['tags']); 
} 

// MY ARRAY XWORDS FOR DEBUG 
// 
// Array ([0] => xavier, celine, marise, leon, john, cathy, polux, maurice 
// 

Mon script a besoin de trouver la première lettre de chaque mot dans cette liste et vérifier s'il correspond avec A/B/C (i créer une page d'index AZ)

// COUNT $XWORDS VALUE 
$total = count($xwords); 
// total =1 
for($i=0; $i < $total; $i++) 
{ 
$wtags = explode(",",$xwords[$i]); 
// wtags = Array ([0] => xavier [1] => celine [2] => marise...) 
    while (list($idx,$val) = each($wtags)) { 
    echo $val{0}."<br>"; 
    echo substr($val,0,1)."<br>"; 
    } 
} 

echo $val{0}."<br>"; OU echo substr($val,0,1)."<br>" me donner juste x et rien après (tout en me donner la première lettre du premier enregistrement dans le tableau ... étonnant :))

Peut-être vous pouvez me aider à trouver une solution . Merci

Répondre

2

Le problème avec votre code est qu'il génère:

Array ([0] => "xavier" [1] => "celine" [2] => "Marise" .. .)

Donc $ val [0] = "". Essayez d'ajuster ($ val):

$val = trim($val); 
print $val[0]; 
+0

Bonne prise, +1. –

0
$sum = array(); 
foreach($wtags as $tag){ 
    $tag = trim($tag); 
    empty($sum[$tag{0}]) ? // if we don't have a $sum element for this letter 
       $sum[$tag{0}] = 1 : // we initialize it 
       $sum[$tag{0}]++;  // else, we sum 1 element to the count. 
    //$tag{0} is the first letter. 
} 

// the array $sum has the total of tags under each letter 
// 
// $sum[x] = 1 
// $sum[c] = 2 
// $sum[m] = 2 
// $sum[l] = 1 
// $sum[j] = 1 
// $sum[p] = 1 
+0

Que signifie cette syntaxe d'accolade? –

+0

Cela signifie "le caractère à la position 0 de cette chaîne" –

+0

Merci ... donc dans les cas où 'x [i]' pourrait être mal interprété comme un élément de tableau, vous pouvez utiliser 'x {i}'. –