-3

I have the following URL: myexample.com/?city=Miami

and a large array (23k)

$e = $_GET["city"];


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

I'm looking for a solution to dynamically create a new array of cities that matches the state of the city in the URL, and echo all the cities from that state.

In other words:
if myexample.com/?city=NOLA, I would like to echo "Baton Rouge" and "NOLA" (from Luisiana)
if myexample.com/?city=Miami, echo "Key West" and "Miami" (from Florida)
etc.

There are quite a few similar questions answered already (here, here, but looping is not one of strengths (beginner).

Thank you.

EDIT1:

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

Result: Array ( [0] => Array ( [0] => Miami [1] => Florida ) )

Mr Bela
  • 1
  • 2
  • 5
    And what do you want from us? Write you the codez? – u_mulder May 28 '17 at 10:51
  • Show us what have you tried till now? If you are expecting someone to answer and write code for you, not the right place. – Milan Chheda May 28 '17 at 12:50
  • What I tried is to check if $e exist in $myArray and add it to a new array. (see edit 1) – Mr Bela May 29 '17 at 10:10
  • It also might be better if you show what you get (your url params), what you want (how the result should look like) and what you tried. – Jason Schilling May 29 '17 at 10:19
  • @u_mulder Not really, just the right direction. Perhaps my array is not built the same way as I've seen in other examples. I searched for similar solutions on here and Google (up to the 150th result) using different search terms, and the code I have so far is either an error or not showing what I'm after. – Mr Bela May 29 '17 at 10:23

1 Answers1

0

First of all I would restructure your myArray in something like the following:

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

after that you can better handle the input and give an easier output

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

(the code is not tested!)

Manual:

http://php.net/in_array

http://php.net/empty

Jason Schilling
  • 475
  • 6
  • 19
  • Thank you, it work's. What I was after is the last part where I added: echo "Other cities in ".$state.":
    "; for($x=0;$x".$resultCities[$x]."
    "; } }
    – Mr Bela May 29 '17 at 10:48