dongzhong8691 2015-10-29 19:07
浏览 35

检查数组中是否存在与字符串匹配的键

I receive a feed from a 3rd party, which includes a location string for each object.

I loop through each object, checking the location and storing a latitude/longitude value for it based on matching the location to a locations DB I have.

Sometimes, the location string isn't well formatted/ there are too many variations/ the locations DB just doesn't match anything.

I have setup an array in a config file of 'special locations' that I want to be able to match against should the location match fail.

e.g, in my array I will have:

Aberdeen => ( 
     latitude => LATVAL,
     longitude => LONGVAL
),
Greater London => (
     latitude => LATVAL,
     longitude => LONGVAL
)

and I may get an object from the feed with a location string of

'Aberdeen (EU Travel)'

and another may be:

'Aberdeen Airport, Grampia'

In these cases, I would want to match Aberdeen, and be able to get the associated lat/lon.

How can I check my array, to see if any keys are within the location string? or the location string contains a key from the array

  • 写回答

1条回答 默认 最新

  • dounianluo0086 2015-10-29 19:26
    关注

    What if we approached it like this?

    // Function to compare and find and return;
    function checkIfContains($find,$locations)
    {
        $newArray = array();
        foreach($locations as $loc => $value)
        {
            if (strpos($loc,$find) !== false) {
                $newArray[] = $value;
            }
        }
        return $newArray;
    }
    
    // Sample data
    $locations = array(
        'Aberdeen' => array(
            'latitude' => '123.123123213',
            'longitude' => '5.34234324'
        ),
        'Aberdeen (EU Travel)' => array(
            'latitude' => '112.4344443',
            'longitude' => '1.23444322'
        ),
        'Aberdeen Airport, Grampia' => array(
            'latitude' => '6.434443',
            'longitude' => '23.34445'
        ),
        'Greater London' => array(
            'latitude' => '13.545453',
            'longitude' => '11.233467'
        )
    );
    
    // Filtered array with only the Aberdeen Elements
    $filteredArray = checkIfContains('Aberdeen' , $locations);
    
    // Debugging Test
    foreach($filteredArray as $loc)
    {
      echo $loc['latitude'] .',', $loc['longitude'].'<br>';
    }
    

    This allow us to find results by a partial string match.

    let me know if this something like this works.

    评论

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计