DEV Community

Cover image for Make Title Path for Detail Pages
andysaktia
andysaktia

Posted on

Make Title Path for Detail Pages

I have some data arrays, and I want to process it into a special url path for name ortitle. The array data is like the following.

Example Array

array ( 0 => array ( 'name' => 'Alryntop', 'gender' => 'Laki-Laki', 'age' => '20', 'city' => 'Jakarta', ), 1 => array ( 'name' => 'Andre Tau Aja', 'gender' => 'Laki-Laki', 'age' => '33', 'city' => 'Jakarta', ), ); 
Enter fullscreen mode Exit fullscreen mode

Function

So I only process it using the PHP as follows; Where my spaces change to - and words become lowercase.

Script:

function getArrWithPath(array $arr, $position = '') { foreach ($arr as $key => $item) { if($position == ''){ $target = $item; }else{ $target = $item[$position]; } $target = strtolower($target); $target = str_replace(' ', '-', $target); $target = preg_replace('/[^A-Za-z0-9\-]/', '', $target); $arr[$key][$position.'_path'] = $target; } return $arr; } 
Enter fullscreen mode Exit fullscreen mode

Result:

array ( 0 => array ( 'name' => 'Alryntop', 'gender' => 'Laki-Laki', 'age' => '20', 'city' => 'Jakarta', 'name_path' => 'alryntop', ), 1 => array ( 'name' => 'Andre Tau Aja', 'gender' => 'Laki-Laki', 'age' => '30', 'city' => 'Jakarta', 'name_path' => 'andre-tau-aja', ), ); 
Enter fullscreen mode Exit fullscreen mode

With this result I can process the more specific detail page leads to the data in choice. Or the reader has better suggestions, discussing bellow please!

Top comments (0)