php - How can I filter values from an array and then sort them by a custom order? -
i parsing json file , have filtered out values wanted based on key loop through create variables other key values want. have sorted not sure how order displays in order want. there simplified way filter , order in 1 quick function or need order separately , if best approach?
here snippet code filtering array based on "event" key before loop. order below order in want them displayed when output too.
$str = file_get_contents($url); // put contents of file variable $o=json_decode($str,true); $features=$o['features']; // lets filter response values want $filtered = array_filter($features,function($el){ $alerts = array('tornado warning', 'severe thunderstorm warning', 'hurricane warning', 'tropical storm warning', 'flash flood warning', 'flood warning', 'tornado watch', 'severe thunderstorm watch', 'hurricane watch', 'tropical storm watch', 'flash flood watch'); return in_array($el['properties']['event'],$alerts); });
use array_filter()
, array_flip()
, , usort()
:
$alerts = array( 'tornado warning', 'severe thunderstorm warning', 'hurricane warning', 'tropical storm warning', 'flash flood warning', 'flood warning', 'tornado watch', 'severe thunderstorm watch', 'hurricane watch', 'tropical storm watch', 'flash flood watch', ); // filter features, remove not of of desired event types $alertfeatures = array_filter($features, function(array $feature) use ($alerts) { $eventtype = $feature['properties']['event']; return in_array($eventtype, $alerts); }); // flip alerts, mapping names of alerts index in array (we'll use order) $order = array_flip($alerts); // sort elements order of event type desired usort($alertfeatures, function (array $a, array $b) use ($order) { $eventtypea = $a['properties']['event']; $eventtypeb = $b['properties']['event']; return $order[$eventtypea] - $order[$eventtypeb]; }); var_dump($alertfeatures);
for reference, see:
Comments
Post a Comment