Skip to content

Instantly share code, notes, and snippets.

@akmandev
Last active February 6, 2023 04:09
Show Gist options
  • Save akmandev/303e4d23f6640e6342e4 to your computer and use it in GitHub Desktop.
Save akmandev/303e4d23f6640e6342e4 to your computer and use it in GitHub Desktop.
<?php
namespace App\Helpers;
abstract class RecursiveCategories
{
public static function getChildren($items, $parent = 0)
{
$element = [];
foreach ($items as $item) {
if ($item['parent_id'] == $parent) {
$element[$item['id']] = $item;
$element[$item['id']]['children'] = self::getChildren($items, $item['id']);
}
}
return $element;
}
/**
* @param $items
* @param null $selectedCats
* @param string $inputName
* @param string $disabledCats
* @return string
*/
public static function buildCategoryTree($items, $selectedCats=null, $inputName='categories', $disabledCats = null)
{
$tree = '<ul>';
$selectedCategories = explode(',', $selectedCats);
$disabledCategories = explode(',', $disabledCats);
foreach($items as $item){
if(in_array($item['id'], $disabledCategories)){
$disabled = 'disabled="disabled"';
}else{
$disabled = '';
}
if(in_array($item['id'], $selectedCategories)){
$selected = 'checked="checked"';
}else{
$selected = '';
}
$tree .= '<li><input '.$disabled.' '.$selected.' type="checkbox" value="'.$item['id'].'" name="'.$inputName.'[]"><span>'.$item['title'].'</span>';
if(!empty($item['children'])){
$tree .= self::buildCategoryTree($item['children'], $selectedCats, $inputName);
}
$tree .= '</li>';
}
$tree .='</ul>';
return $tree;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment