Turn Over Address Components to an Array


/ Published in: PHP
Save to your folder(s)

Breaks up an address (in this case returned by Advanced Custom Fields Location plugin) into it's components. Additionally, sorts a multidimensional array of locations alphabetically by state. This works for basic addresses assuming that address is in the format 'street, city, state, zip, country.' I've written a more extensive version of this snippit that uses Google Geocoding to get the address components and store them in a Wordpress database as meta data.


Copy this code and paste it in your HTML
  1. function break_address( $loc )
  2. {
  3. $components = explode( ',' , $loc );
  4. $state_zip = explode( ' ' , trim( $components[2] ) );
  5. $components_array = array(
  6. 'street' => trim( $components[0] ),
  7. 'city' => trim( $components[1] ),
  8. 'state' => $state_zip[0],
  9. 'zip' => $state_zip[1],
  10. 'country' => trim( $components[3] )
  11. );
  12. return $components_array;
  13. }
  14.  
  15. $locations = array();
  16. $location = get_field( 'location_field' );
  17. $location = $location[ 'address' ];
  18. $locations[ 0 ] = break_address( $location );
  19.  
  20. usort( $locations , function( $a , $b )
  21. {
  22. return $a[ 'state' ] - $b[ 'state' ];
  23. });
  24.  
  25. var_dump( $locations );

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.