dynamic url(separated by slash) paramters get to array? (eg : /category,cat1,cat2/types,type1,type2)

Viewed 80

have a good day guys!, im currently working on eCommerce like product filter,controller get request from front-end main category and parameters separated by slash('/'). URL parameters send like this:

example.com/skin-care/categories,facial-cleansers-toners/collection,classic/skin-types,normal,soft

these URL open when user select attributes from filter. so after example.com/skin-care/ is totally dynamic.

/skin-care - main category after first slash separate, all parameters dynamic attributes. eg : /{attribute},value1,value1,..

so above examples have 1 main category slug and, 3 attributes (categories,collection,skin-types) and values of that attributes

i just need get these attributes to Associative array. just like this:

$attributes = ['categories' => ['facial-cleansers-toners'],
        'collection' => ['classic'],
        'skin-types' => ['normal','soft']
        ];
        
    

thank you

1 Answers

your url is:

$static_url = "http://example.com/skin-care/categories,facial-cleansers-toners/collection,classic/skin-types,normal,soft";

first of all, we have to parse your URL to get our needed parameters :

$url_components = parse_url($static_url);

this variable outputs 3 items scheme, host and path. we need just path from here, so:

$url_path = $url_components['path'];

in the next level, we need to remove the first / character from the string and explode the string by / character:

$url_path_params = ltrim($url_path, $url_path[0]);
$url_attributes = explode('/', $url_path_params);

in this section we have the main category that maybe you need:

$main_category = $url_attributes[0]; // skin-care

we don't need the first item ($main_category = 'skin-care') here so:

array_shift($url_attributes);

in the last step we got the $url_attributes that we need to fill in the attributes array with foreach loop and explode the string by , just like this:

$attributes = [];
foreach ($url_attributes as $attribute_key => $attribute_value) {
    $each_attribute = explode(',', $attribute_value);
    $cat = array_shift($each_attribute);

    $attributes[$cat] = $each_attribute;
}

if you get output from $attributes you got your needed data. in var_dump output this returns:

output

you can access to skin_types by: $attributes["skin-types"].

Check the whole source in PHP Sandbox

Related