DEV Community

Cover image for Make Title Path for Detail Pages
andysaktia
andysaktia

Posted on

4 2

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!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay