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
Check this
or you can try with array_filter
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.)
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()
).https://3v4l.org/skMWu
This produces: