2010-11-29 42 views
0

我對數組很陌生,這超出了我的理解範圍。如何從數組中獲取數據並將其顯示在回顯中。我知道這很簡單!提前致謝! 這裏是低於PHP - 顯示數組中的變量

$string = "John Smith Smithville"; 
$townlist = array("smithville", "janeville", "placeville"); 

function stringSeperation($string, $list) 
{ 
    $result = array(); 

    foreach($list as $item) 
    { 
     $pos = strrpos(strtolower($string), strtolower($item)); 
     if($pos !== false) 
     { 
      $result = array(trim(substr($string, 0, $pos)), trim(substr($string, $pos))); 
      break; 
     } 
    } 

    return $result; 
} 

var_dump(stringSeperation($string, $townlist)); 

回聲名

回聲鎮

關於後續代碼var_dump

array(2) { [0]=> string(10) "John Smith" [1]=> string(10) "Smithville" } 

和代碼, -Dan

回答

2
$strs = stringSeperation($string, $townlist); 
echo $strs[0] . "\n"; 
echo $strs[1] . "\n"; 
3
$result = stringSeperation($string, $townlist); 

echo $result[0]; // prints the name 
echo $result[1]; // prints the town 

foreach($result as $value) { 
    echo $value; 
} 

Learn more about arrays.

注:換行,您應該使用取決於你是否想生成HTML或不PHP_EOL<br />

+0

作品!非常感謝你! – Dan 2010-11-29 11:28:13

1

echo arrayName[i];其中i是您希望輸出的數組的索引。

所以在你的情況下,echo $result[0];會輸出名字,echo $result[1];會輸出城鎮。

2
$data = stringSeperation($string, $townlist); 

$name = $data[0]; 
$town = $data[1]; 

echo $name; 
echo $town; 
0

如果你想呼應整個數組做到這一點

$count = count($townlist) 

for($i=0; $i<$count; $i++){ 
    echo $townlist[$i]; 
} 

您可以簡單地echo數組的元素,如果你知道做這個

echo $townlist[0]; //this will echo smithville

關鍵這會輸出

smithville 
janeville 
placeville 

希望能幫到你!

0
$count = count($result); 

for($counter = 0;$counter<$count;$counter++) 
{ 
    echo $result[$counter]; 
} 

foreach($result as $value) 
{ 
    echo $value; 
}