Home > Back-end >  How can I turn this PHP numeric array into an array of objects with specific properties?
How can I turn this PHP numeric array into an array of objects with specific properties?

Time:01-09

I am working on a blogging application in Laravel 8.

The application supports themes. In a nutshell, theme support works like this:

In the views directory, I have the directory containing the views of every theme.

enter image description here

In public\themes I keep the assets (CSS, Javascript) of every theme.

enter image description here

In the SettingsController controller I have, among others, a variable named $theme_directory, which contains the name of the directory of the current theme. I use this variable in the theme view, like this, for instance:

<link href="{{ asset('themes/' . $theme_directory . '/css/clean-blog.min.css') }}" rel="stylesheet">    

From the "Settings" section I can set the current theme.

enter image description here

I am now trying to replace the text field where I type the theme's (directory) name with a select-box. For this purpose I have:

public function themes() {
    $themes = [];
    $themes_path = Config::get('view.paths')[0] . '\themes';
    foreach(File::directories($themes_path) as $theme) {
        array_push($themes, array_reverse(explode('\\', $theme))[0]);
    }
    return $themes;
}

I pass the arary of themes to the view:

public function index() {
  $settings = Settings::first();
  return view('dashboard/settings', [
    'settings' => $settings, 
    'themes' => $this->themes()
  ]);
} 

The above method returns an array like this:

[▼
    0 => "calvin"
    1 => "clean-blog"
]

The goal

I need to turn that into am array of objects instead, with the properties slug ("clean-blog") and name ("Clean blog") for each member of the array above, so that I can use it like this in the view (form):

<select name="theme_directory" id="theme" >
          <option value="">Pick a theme</option>
          @foreach($themes as $theme)
          <option value="{{ $theme->slug }}" {{ $theme->slug == $settings->theme_directory  ? 'selected' : '' }}>{{ $theme->name }}</option>
          @endforeach
</select>

How can I achieve that?

CodePudding user response:

Just transform your slug into a name by replacing dashes by spaces, then upper case the first lerter (ucfirst function).

Then put into an associative array (I'm using compact functiom here to simplify)

public function themes() {
    $themes = [];
    $themes_path = Config::get('view.paths')[0] . '\themes';
    foreach(File::directories($themes_path) as $theme) {
        $slug = array_reverse(explode('\\', $theme))[0];
        $name = ucwords(str_replace('-', ' ', $slug));
        $themes[] = (object)compact('slug', 'name');
    }

    return $themes;
} 
  • Related