I'd like to be able to search for the array with the title Seattle, which will be set by a variable. Then return the x or y coordinate for that array. I've tried 5 or 6 different ways of trying to locate it without any luck.
This is the query I am using and how I am printing my array:
global $wpdb;
$myquery = $wpdb->get_row("SELECT * FROM wp_maps WHERE title = 'Test Map'");
$mymap = $mylink->data;
print_r($mymap);
This is the actual output.
{ "title":"USA", "location":"World", "levels":[ { "id":"states", "title":"States", "locations":[{"id":"bhAAG","title":"Seattle","description":"The City of Goodwill","x":47.6097,"y":122.3331},{"id":"biAAG","title":"Portland","description":"Portland, Maine. Yes. Life’s good here.","x":43.6667,"y":70.2667}] } ] }
Same output (formatted for easier viewing).
{
"title":"USA",
"location":"World",
"levels":[
{
"id":"states",
"title":"States",
"locations":[
{
"id":"bhAAG",
"title":"Seattle",
"description":"The City of Goodwill",
"x":47.6097,
"y":122.3331
},
{
"id":"biAAG",
"title":"Portland",
"description":"Portland, Maine. Yes. Life’s good here.",
"x":43.6667,
"y":70.2667
}
]
}
]
}
Any help would be appreciated.
Your myMap
data is in JSON format. You can json_decode it into an array and then search all locations for an array with the specified title:
$myMap = '{ "title":"USA", "location":"World", "levels":[ { "id":"states", "title":"States", "locations":[{"id":"bhAAG","title":"Seattle","description":"The City of Goodwill","x":47.6097,"y":122.3331},{"id":"biAAG","title":"Portland","description":"Portland, Maine. Yes. Life’s good here.","x":43.6667,"y":70.2667}] } ] }';
// Convert JSON and grab array of locations
$array = json_decode($myMap, true);
$locations = $array['levels'][0]['locations'];
// What we are looking for
$title = 'Seattle';
// Search locations
foreach ($locations as $location) {
if ($location['title'] == $title) {
$x = $location['x'];
$y = $location['y'];
}
}
echo "x = $x, y = $y", PHP_EOL;
Output:
x = 47.6097, y = 122.3331
Compact solution PHP5 >= 5.3
$term = ''; // term being used to search
if(isset($mymap['levels']) && isset($mymap['levels']['locations'])){
$locations = $mymap['levels']['locations'];
// filtered will be an array of x, y values
$filtered = array_map(function($location){
return [ 'x' => $location['x'], 'y' => $location['y']]; // transform into required format
}, array_filter($locations, function($location) use ($term){ // filter by title
return $location['title'] === $term;
}));
}