php 如果 id 正好是 x
php if id is exactly x
我正在使用以下内容检查网址中的动态城市 ID,如下所示:
http://website.com/homes-for-sale-results/?cityId=10008&propertyType=SFR%2CCND&minListPrice=&ma
我用的php是这样的:
if (strpos($url, "cityId=9918")) {
$cityName = "Allenhurst";}
} elseif (strpos($url, "cityId=1000")) {
$cityName = "Highlands";
} elseif (strpos($url, "cityId=10009")) {
$cityName = "Holmdel";
除非 cityid 包含另一个城市的 id,否则此方法有效,因为一个城市有 4 位数字,而其他城市有 5 位数字。在上面的示例中:Highlands = "1000" and "Holmdel = "10009".
如何查询准确的 cityid?
是的,strpos
不是一个很好的解决方案。
您可以先将问题分解成几个较小的部分以使其更容易。
因为它是 URL,您可以使用 parse_url()
first to extract the query string from the URL in a deterministic fashion. Then you'd be able to parse the individual pieces of that query string into individual data points using something like parse_str()
。所以从那里你可以直接将数字与特定值进行比较。
$url = "http://website.com/homes-for-sale-results/?cityId=10008&propertyType=SFR%2CCND&minListPrice=&ma";
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $data);
$cityId = $data["cityId"];
if ($cityId == 9918) {
$cityName = "Allenhurst";
} elseif ($cityId == 1000) {
$cityName = "Highlands";
} elseif ($cityId == 10009) {
$cityName = "Holmdel";
}
所以在第一步中,$query
为我们提供了来自 URL 的确切查询字符串(?
之后的所有内容)。然后 $data
给你每个 name/value 对,在查询字符串中,作为一个数组。这意味着最后,您可以通过 $data["cityId"]
从查询字符串中获取 cityId
的确切值(我在这里只是分配给 $cityId
)并将其用于直接比较。
我正在使用以下内容检查网址中的动态城市 ID,如下所示:
http://website.com/homes-for-sale-results/?cityId=10008&propertyType=SFR%2CCND&minListPrice=&ma
我用的php是这样的:
if (strpos($url, "cityId=9918")) {
$cityName = "Allenhurst";}
} elseif (strpos($url, "cityId=1000")) {
$cityName = "Highlands";
} elseif (strpos($url, "cityId=10009")) {
$cityName = "Holmdel";
除非 cityid 包含另一个城市的 id,否则此方法有效,因为一个城市有 4 位数字,而其他城市有 5 位数字。在上面的示例中:Highlands = "1000" and "Holmdel = "10009".
如何查询准确的 cityid?
是的,strpos
不是一个很好的解决方案。
您可以先将问题分解成几个较小的部分以使其更容易。
因为它是 URL,您可以使用 parse_url()
first to extract the query string from the URL in a deterministic fashion. Then you'd be able to parse the individual pieces of that query string into individual data points using something like parse_str()
。所以从那里你可以直接将数字与特定值进行比较。
$url = "http://website.com/homes-for-sale-results/?cityId=10008&propertyType=SFR%2CCND&minListPrice=&ma";
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $data);
$cityId = $data["cityId"];
if ($cityId == 9918) {
$cityName = "Allenhurst";
} elseif ($cityId == 1000) {
$cityName = "Highlands";
} elseif ($cityId == 10009) {
$cityName = "Holmdel";
}
所以在第一步中,$query
为我们提供了来自 URL 的确切查询字符串(?
之后的所有内容)。然后 $data
给你每个 name/value 对,在查询字符串中,作为一个数组。这意味着最后,您可以通过 $data["cityId"]
从查询字符串中获取 cityId
的确切值(我在这里只是分配给 $cityId
)并将其用于直接比较。