通过在多维数组中搜索标题来返回值

时间:2015-03-10 16:44:06

标签: php arrays variables multidimensional-array

我希望能够搜索标题为Seattle的数组,该数组将由变量设置。然后返回该数组的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
                }
            ]
        }
    ]
}

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:2)

您的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

答案 1 :(得分:0)

紧凑型解决方案 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()