2017-05-28 38 views
-3

我有以下网址:myexample.com/ 城市=迈阿密从多维数组新的阵列 - URL解析

大阵(23K)

$e = $_GET["city"]; 


$myArray = array 
(
array ("Miami","Florida"), 
array ("Key West","Florida"), 
array ("NOLA", "Luisiana"), 
array ("Baton Rouge","Luisiana") 
); 

我?寻找一种解决方案,动态创建一个与URL中城市状态相匹配的新城市阵列,并呼应来自该州的所有城市。

换句话说:
如果myexample.com/?city=NOLA,我想回声 “巴吞鲁日” 和 “NOLA”(来自Luisiana)
如果myexample.com/?city=Miami,回声“基韦斯特”和“迈阿密”(来自佛罗里达州)

有不少类似的问题已经(here回答,here,但循环不是强项(初级)之一。

谢谢

EDIT1:

$resArray = array(); 
foreach($myArray as $arr) { 
    if(in_array($e, $arr)) 
     $resArray[] = $arr; 
} 
print_r($resArray); 

结果:阵列([0] =>数组([0] =>迈阿密[1] =>佛罗里达))

+5

那你要我们什么呢?写你的codez? –

+0

告诉我们你到现在为止尝试过什么?如果您希望某人为您回答和编写代码,则不是正确的地方。 –

+0

我试过的是检查$ e是否存在于$ myArray中并将其添加到新数组中。 (见编辑1) –

回答

0

首先我会调整你myArray在类似如下:

$stateAndCities = [ 
    "Florida" => ["Miami","Key West"], 
    "Luisiana" => ["NOLA", "Baton Rouge"] 
]; 

后,你可以更好地处理输入,并给予一个更简单的输出

$city = $_GET["city"]; 
$resultCities = []; 
$resultState = ""; 

// Loop over all states with their cities 
foreach($stateAndCities as $state => $cities) { 
    if(in_array($city, $cities)){ // if the given $city is in the $cities? 
     $resultCities = $cities; 
     $resultState = $state; 
     break; 
    } 
} 

if(!empty($resultState) && !empty($resultCities)){ // ensure that the city was found in any state 
    echo $resultState; 
    print_r($resultCities); 
} 

(代码没有测试!)

手册:

http://php.net/in_array

http://php.net/empty

+0

谢谢,它的工作。我所追求的是我添加的最后一部分: 回声“在其他城市”。$ state。“:
”; \t为($ X = 0; $ X <计数($ resultCities); $ X ++){ \t \t回声 “
” $ resultCities [$ X]。“
”; \t} } –