return 通过在多维数组中搜索标题的值

return value by searching for title inside a multidimensional array

我希望能够搜索标题为 Seattle 的数组,该数组将由变量设置。然后 return 该数组的 x 或 y 坐标。我已经尝试了 5 或 6 种不同的方法来尝试找到它,但没有任何运气。

这是我正在使用的查询以及我如何打印数组:

global $wpdb;
$myquery = $wpdb->get_row("SELECT * FROM wp_maps WHERE title = 'Test Map'"); 
$mymap =  $mylink->data;

print_r($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}] } ] }

相同的输出(格式化以便于查看)。

{
    "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
                }
            ]
        }
    ]
}

如有任何帮助,我们将不胜感激。

您的 myMap 数据采用 JSON 格式。您可以 json_decode 将其放入数组中,然后在所有 位置 中搜索具有指定标题的数组:

$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;

输出:

x = 47.6097, y = 122.3331

紧凑解 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;
    }));
}

array_filter() array_map()