Home > database >  Saving only a specific part of a json response as a new variable
Saving only a specific part of a json response as a new variable

Time:10-19

I have a very simple question I think, but since im very new I dont really know where to start to look for an answer.

[{"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"},

Lets say I have a JSON response like this

$data = json_decode($json, true);

foreach ($data as $result)
    if ($result['state'] == 'Nordrhein-Westfalen')
    echo($result['name'] . ", ");

I can display a list of all names of cities that are in the state Nordrhein-Westfalen

But how can I, instead of echoing the list, save that result as a new variable?

Ive tried a few ways but I can't get it to work.

CodePudding user response:

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

CodePudding user response:

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

  • Related