Wednesday, 15 July 2015

php - Make URI Segment Parameters Optional -



php - Make URI Segment Parameters Optional -

i developing application in codeigniter have database of articles. want able filter articles type(article, opinion, review, media) , sort either date, views, or number of comments. these parameters through uri. want able dynamically convert these uri's script's variables combination of parms possible, except more 1 type or more 1 sort. example, uri may contain type, no sort... or may contain sort no type... or contain both or none. how uri's right now:

articles/type:media/sort:date-desc articles/sort:comments-asc articles/sort:views-desc ... etc.

this current script have:

$uri = 'type:media/sort:views-desc'; $uri = explode('/', $uri); $allowed_types = array('article', 'review', 'opinion', 'media'); $allowed_sorts = array('date-asc', 'date-desc', 'views-asc', 'views-desc', 'comments-asc', 'comments-desc'); if(count($uri) > 0){ for($i=0;$i<=count($args);$i++){ $argument = explode(':', $args[$i]); if($argument[0] == 'type'){ if(in_array($argument[$i], $allowed_types)){ $type = $argument[1]; } } else if($argument[0] == 'sort'){ if(in_array($argument[$i], $allowed_sorts)){ $sort_by = explode('-', $argument[1]); $sort_by_what = $sort_by[0]; $sort_by_how = $sort_by[1]; } } } } show_error('type: '.$type.'... sort by: '.$sort_by_what.'-'.$sort_by_how);

i getting few errors 3 argument vars $type, $sort_by_what, $sort_by_how not defined , undefined offset: 1. ideas on how prepare this?

you using variables outside scope. if want utilize them in scope, create sure declared there.

try adding:

$sort_by = "" ; $sort_by_what = "" ; $sort_by_how = "" ;

outside if status clause.

i'd suggest check size of array returned explode call, create sure it's not empty. think causing out-of-bounds error (undefined offset: 1)

so, code should like:

$uri = 'type:media/sort:views-desc'; $uri = explode('/', $uri); $sort_by = ""; $sort_by_what = ""; $sort_by_how = ""; $allowed_types = array('article', 'review', 'opinion', 'media'); $allowed_sorts = array('date-asc', 'date-desc', 'views-asc', 'views-desc', 'comments-asc', 'comments-desc'); if (count($args) > 0) { ($i = 0; $i <= count($args); $i++) { $argument = explode(':', $args[$i]); if (count($argument) > 0) { if ($argument[0] == 'type') { if (in_array($argument[$i], $allowed_types)) { $type = $argument[1]; } } else if ($argument[0] == 'sort') { if (in_array($argument[$i], $allowed_sorts)) { $sort_by = explode('-', $argument[1]); if (count($sort_by) > 0) { $sort_by_what = $sort_by[0]; $sort_by_how = $sort_by[1]; } else { show_error("can't parse sorting parameters!"); } } } } } show_error('type: ' . $type . '... sort by: ' . $sort_by_what . '-' . $sort_by_how); }

i don't know if snippet of code, or whole code, did variable $args come ?

php codeigniter uri

No comments:

Post a Comment