将多个字符串转换为多维数组

时间:2016-01-15 17:42:45

标签: php multidimensional-array url-routing

我正在尝试制作一个花哨的路由器,其想法如下:

'{subdomain}.{request type}.{uri}' => '{controller}@{method}'

到目前为止我所拥有的是:

routes.php文件

return [
    '.GET.'                 => 'home@index',
    '.GET.user/*'           => 'user@viewProfile',
    '.GET.user/*/comments'  => 'user@viewComments',
];

Router.php

class Router {
    private $routes, $uri, $subdomain;

    public function __construct() {
        $this->routes    = $this->parseRoutes(require 'app/routes.php');
        $this->subdomain = $this->getSubdomain();
        $this->uri       = $this->getUri();
    }

    private function getSubdomain() {
        $url = explode('.', $_SERVER['SERVER_NAME']);
        return (count($url) >= 3) ? current($url) : '';
    }

    private function getUri() {
        $uri = preg_replace('#\/{2,}#', '/', urldecode($_SERVER['REQUEST_URI']));
        return trim(str_replace(' ', '', $uri), '/');
    }

    private function parseRoutes($routes) {
        $return = [];
        foreach($routes as $route => $controller) {
            $route = explode('.', $route);
            $uri = explode('/', $route[2]);
            $return[$route[0]][$route[1]][$route[2]] = $controller;
        }
        return $return;
    }

    public function getController() {

    }

}

parseRoutes方法需要将数组转换为:

[
    '' => [
        'GET' => [
            '' => 'home@index',

            'user' => [
                '*' => [
                    ''         => 'user@viewProfile',
                    'comments' => 'user@viewComments'
                ],
            ],

        ],
    ],
]

我可以让subdomainrequest type正常工作,但我不知道如何将uri转换为这样的格式。

1 个答案:

答案 0 :(得分:0)

protected $controller = 'home';
protected $method = 'index';
protected $params = [];
public function __construct(){
this->parseUrl();
// also add if statements to check if controller, method exist

// CHECK IF PARAMETERS EXIST, IF YES, GET ARRAY OF PARAMENTERS, OTHERWISE SET   EMPTY ARRAY
$this->params = $url ? array_values($url) : [];
call_user_func_array([$this->controller, $this->method], $this->params);

} // end of constructor
// SPLITTING URL INTO ARRAY (url[0] / url[1] / url[2] / ...)
// A.K.A.(controller/method/property1/property2/...)
public function parseUrl(){
if(isset($_GET['url'])){
    return $url = explode('/', filter_var(rtrim($_GET['url'], '/'), FILTER_SANITIZE_URL));
} // end of if
} // end of function parseUrl