duandong9195 2015-11-02 18:44
浏览 94
已采纳

PHP URL数组返回先前路由数组的结果

I use URL routing on my website and this is the code I use:

/* TURN FULL URL INTO --> /example/example2/example3 */
function getCurrentUri()
{
    $basepath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
    $uri = substr($_SERVER['REQUEST_URI'], strlen($basepath));
    if (strstr($uri, '?')) $uri = substr($uri, 0, strpos($uri, '?'));
    $uri = '/' . trim($uri, '/');
    return $uri;
}
$base_url = getCurrentUri();
$routes = array();
$routes = explode('/', $base_url);
foreach($routes as $route)
{
    if(trim($route) != ''){
        array_push($routes, $route);
    }
}

For some reason it outputs the following when using var_dump() on $routes[0], $routes[1], $routes[2] and $routes[3]. This is while being on the following website: http://localhost/tutorials/

string '' (length=0)
string 'tutorials' (length=9)
string 'tutorials' (length=9)
null

How can I solve this routing problem?

  • 写回答

1条回答 默认 最新

  • dongzi8191 2015-11-02 18:59
    关注

    If I understand it correctly:

    1. You created array variable $routes.
    2. Then you fill that array with strings from explode('/', $base_url).
    3. You iterate that array and if string is not '', then you push that string onto the end of array.

    To avoid this, you can use array_pop() instead of array_push() and change condition from trim($route) != '' to trim($route) === '' || trim($route) === null. Second condition is needed to remove null element from array.

    Or you can assign explode('/', $base_url) to different variable, e.g. $explodedUrls and iterave over its.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统