开发者

Can I generate an array based on url path?

I have a path like:

/blog/2/post/45/comment/24

Can I have an ar开发者_如何学JAVAray depends on what I have on url, like :

$arr = array('blog'=>'2','post'=>'45','comment'=>'24');

But it should depend on variable passed:

/blog/2 should produce $arr = array('blog'=>'2');

Is this possible to create dynamic array?


You could try something like this:

function path2hash($path) {
  // $path contains whatever you want to split
  $chunks = explode('/', $path);

  $result = array();
  for ($i = 0; $i < sizeof($chunks) - 1; $i+=2)
    $result[$chunks[$i]] = $chunks[$i+1];

  return $result;
}

You could then use parse_url to extract the path, and this function to turn it into the desired hash.


First use $_SERVER['REQUEST_URI'] to find the current path.

now, you can use explode and other string functions to produce the array...

If you need a working example, Ill try and post one.

EDIT:

$path=explode('/',$path);

$arr=array(
$path[0]=>$path[1],
$path[1]=>$path[2]);

or don't know how long it is...

$arr=array();
for ($i=0; $i+1<count($path);i+=2)
$arr[$path[$i]]=$path[$i+1];


Here's a simple example trying to solve the issue. This will put the arguments in the "arguments" array, and will contain each combination of key/value in the array. If there's an odd number of arguments, the last element will be ignored.

This uses array_shift() to remove the first element from the array, which then is used as a key in the arguments array. We then remove the next element from the array, yet again using array_shift(). If we find an actual value here (array_shift returns NULL when the array is empty), we create a entry in the arguments array.

$path = '/blog/2/post/45/comment/24';
$elements = explode('/', $path);

// remove first, empty element
array_shift($elements);
$arguments = array();

while($key = array_shift($elements))
{
    $value = array_shift($elements);

    if ($value !== NULL)
    {
        $arguments[$key] = $value;    
    }
}


Not really an answer per se but you may find http://www.php.net/manual/en/function.parse-url.php useful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜