@@ -343,5 +343,58 @@ public static function get2d( $keyField = 'alpha2', $requestedFields = array( 'a
343343 return $ result ;
344344 }
345345
346+ /*
347+ * function getFromContinent()
348+ * @param $key - key field for the array of countries, set it to null if you want array without named indices
349+ * @param $requestedField - name of the field to be fetched in value part of array
350+ * @param $continent - name of continent to use as filter
351+ * @returns array contained key=>value pairs of the requested key and field
352+ * Works exactly as get() above
353+ * But takes an extra param to enable filtering by continent
354+ *
355+ */
356+ public static function getFromContinent ( $ keyField = 'alpha2 ' , $ requestedField = 'name ' , $ continent =null ) {
357+ $ supportedFields = array ( 'alpha2 ' , 'alpha3 ' , 'num ' , 'isd ' , 'name ' , 'continent ' );
358+ $ supportedContinents = array ( 'Africa ' , 'Antarctica ' , 'Asia ' , 'Europe ' , 'North America ' , 'Oceania ' , 'South America ' );
359+
360+ //check if field to be used as array key is passed
361+ if ( !in_array ( $ keyField , $ supportedFields ) ){
362+ $ keyField = null ;
363+ }
364+
365+ //check if field to be used as continent is passed
366+ if ( !in_array ( $ continent , $ supportedContinents ) ){
367+ $ continent = null ;
368+ }
369+
370+ //check if the $requestedField is supported or not
371+ if ( !in_array ( $ requestedField , $ supportedFields ) ){
372+ $ requestedField = 'name ' ; //return country name if invalid/unsupported field name is request
373+ }
374+
375+ $ result = array ();
376+ //copy each requested field from the countries array
377+ foreach ( self ::$ countries as $ k => $ country ){
378+ if ( $ keyField ){
379+ if ( $ continent ) {
380+ if ( $ country ['continent ' ] == $ continent ) {
381+ $ result [ $ country [ $ keyField ] ] = $ country [ $ requestedField ];
382+ }
383+ } else {
384+ $ result [ $ country [ $ keyField ] ] = $ country [ $ requestedField ];
385+ }
386+ } else {
387+ if ( $ continent ) {
388+ if ( $ country ['continent ' ] == $ continent ) {
389+ $ result [] = $ country [ $ requestedField ];
390+ }
391+ } else {
392+ $ result [] = $ country [ $ requestedField ];
393+ }
394+ }
395+ }
396+ return $ result ;
397+ }
398+
346399}
347400
0 commit comments