skip to Main Content

I am very new to php and basically dont know what i’m doing. So I hope my problem has an easy solution.

Im trying to build a subpage on my website where I display and link to other cities on my website, and that entire subpage is supposed to be ordered by states. So all cities in state "x" will be bundled together, and all cities in state "y" and so on.

I am reading out a JSON file that is structured like this :

[{"id":"AA0","name":"Aalen","region":"Süden","state":"Baden-Württemberg","residents":"Aalener"},
{"id":"AB0","name":"Aschaffenburg","region":"Mitte","state":"Bayern","residents":"Aschaffenburger"},
{"id":"AC0","name":"Aachen","region":"Westen","state":"Nordrhein-Westfalen","residents":"Aachener"},
{"id":"B00","name":"Berlin","region":"Osten","state":"Brandenburg","residents":"Berliner"},
{"id":"BA0","name":"Bamberg","region":"Süden","state":"Bayern","residents":"Bamberger"},
{"id":"BB0","name":"Sindelfingen","region":"Süden","state":"Baden-Württemberg","residents":"Sindelfingener"},
{"id":"BI0","name":"Bielefeld","region":"Westen","state":"Nordrhein-Westfalen","residents":"Bielefelder"}]

My logic is supposed to be handled by a controller – this is what I got so far (and its not much, i tried a few things but nothing worked)

controller:

public function states() {
        $json = file_get_contents('https://api.cms.diebestenderstadt.de/cities/v1/');

        $data = json_decode($json, true);

foreach ($data as $result) {
                    if ($result['state'] == 'Sachsen')
                        echo($result['name'] . ", ");
                    elseif ($result['state'] == 'Nordrhein-Westfalen')
                        echo($result['name'] . ", ");
                    elseif ($result['state'] == 'Baden-Württemberg')
                        echo($result['name'] . ", ");
                    elseif ($result['state'] == 'Bayern')
                        echo($result['name'] . ", ");

return view("index.states")->with("states", $data);

In this way, I at least managed to only display all cities of a certain state, but now im lost as how to go on and how to "save" that state-filtered response for later.

I hope I provided all the info you need, the states subpage so far only really has some dummy code that wont help showing off.

If there is more info you need, please let me know and thanks in advance for your help.

2

Answers


  1. Check this

    $data = json_decode($json, true);
    $variable = [];
    foreach ($data as $result)
       if ($result['state'] == 'Nordrhein-Westfalen')
          $variable[] = $result['name'];
    

    or you can try with array_filter

    $variable = array_filter($data, function($item) {
      return $item['state'] == 'Nordrhein-Westfalen';
    });
    
    Login or Signup to reply.
  2. Here’s some demonstrations of using array map/reduce/filter functions to take an array and transform it towards different ends. What you’re trying to do would most likely fit into one of these forms.

    (There’s a link below the code to review what these produce.)

    $townsJson = <<<JSON
    [{"id":"AA0","name":"Aalen","region":"Süden","state":"Baden-Württemberg"},
    {"id":"AB0","name":"Aschaffenburg","region":"Mitte","state":"Bayern"},
    {"id":"AC0","name":"Aachen","region":"Westen","state":"Nordrhein-Westfalen"},
    {"id":"WIT","name":"Witten","region":"Westen","state":"Nordrhein-Westfalen"},
    {"id":"DN0","name":"Düren","region":"Westen","state":"Nordrhein-Westfalen"}]
    JSON;
    
    $towns = json_decode($townsJson, true);
    
    // Add a description to each entry, e.g. map to each entry.
    $towns = array_map(function(array $town) {
        $town['description'] = sprintf(
            '%s is a town in %s (%s).',
            $town['name'],
            $town['state'],
            $town['region']
        );
        
        return $town;
    }, $towns);
    
    // Filter the towns and only return those that start with A.
    $ATowns = array_filter(
        $towns,
        fn(array $town) => strpos($town['name'], 'A') === 0
    );
    
    // Organize the array into regions. 
    $townsByRegion = array_reduce($towns, function(array $found, array $town) {
        $found[$town['region']][] = $town;
        
        return $found;
    }, []);
    

    https://3v4l.org/HZJpG


    Update

    What it sounds like you want is to populate an additional key that combines other keys (a mapping operation, e.g. array_map()), and then to produce a new array with keys that group cities by state (a reduction that produces a wholly new data concept, e.g., array_reduce()).

    $citiesJson = <<<JSON
    [{"id":"AA0","name":"Aalen","region":"Süden","state":"Baden-Württemberg"},
    {"id":"AB0","name":"Aschaffenburg","region":"Mitte","state":"Bayern"},
    {"id":"AC0","name":"Aachen","region":"Westen","state":"Nordrhein-Westfalen"},
    {"id":"WIT","name":"Witten","region":"Westen","state":"Nordrhein-Westfalen"},
    {"id":"DN0","name":"Düren","region":"Westen","state":"Nordrhein-Westfalen"}]
    JSON;
    
    $cities = json_decode($citiesJson, true);
    
    $cities = array_map(function(array $city) {
        $city['city_region_state'] = sprintf(
            '%s, %s, %s',
            $city['name'],
            $city['region'],
            $city['state']
        );
        
        return $city;
    }, $cities);
    
    $citiesByState = array_reduce($cities, function(array $found, array $city) {
        $found[$city['state']][] = $city;
        
        return $found;
    }, []);
    

    https://3v4l.org/skMWu

    This produces:

    {
        "Baden-Wu00fcrttemberg": [
            {
                "id": "AA0",
                "name": "Aalen",
                "region": "Su00fcden",
                "state": "Baden-Wu00fcrttemberg",
                "city_region_state": "Aalen, Su00fcden, Baden-Wu00fcrttemberg"
            }
        ],
        "Bayern": [
            {
                "id": "AB0",
                "name": "Aschaffenburg",
                "region": "Mitte",
                "state": "Bayern",
                "city_region_state": "Aschaffenburg, Mitte, Bayern"
            }
        ],
        "Nordrhein-Westfalen": [
            {
                "id": "AC0",
                "name": "Aachen",
                "region": "Westen",
                "state": "Nordrhein-Westfalen",
                "city_region_state": "Aachen, Westen, Nordrhein-Westfalen"
            },
            {
                "id": "WIT",
                "name": "Witten",
                "region": "Westen",
                "state": "Nordrhein-Westfalen",
                "city_region_state": "Witten, Westen, Nordrhein-Westfalen"
            },
            {
                "id": "DN0",
                "name": "Du00fcren",
                "region": "Westen",
                "state": "Nordrhein-Westfalen",
                "city_region_state": "Du00fcren, Westen, Nordrhein-Westfalen"
            }
        ]
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search