Skip to content
Advertisement

checkbox print custom array E.g. if chooses Mon, Wed, Fri, Sat, Sun

I have checkbox like this:

enter image description here

E.g. if chooses Mon, Wed, Fri, Sat, Sun. return Mon, Wed, Fri – Sun

E.g. if chooses Sat, Sun. return Sat – Sun

E.g. if chooses Mon, Tue, Thu, Sat, Sun return Mon, Tue, Thu, Sat, Sun

How can I implement that? Is this possible?

$data = [
'get_day_for_route'            => (object)[
    'number_day'    => 1,
    'name_day'      => 'Mon'
],
(object)[
    'number_day'    => 2,
    'name_day'      => 'Tue'
],
(object)[
    'number_day'    => 5,
    'name_day'      => 'Fri'
],
(object)[
    'number_day'    => 6,
    'name_day'      => 'Sat'
],
(object)[
    'number_day'    => 7,
    'name_day'      => 'Sun'
 ],
 ];
 foreach($data as $result)
 {
  $day_result[] = $result->name_day;
 }
 echo implode(', ',$day_result);

Advertisement

Answer

this is function in javascript

const renderDay = (hari: any) => {
    hari = hari.sort((a,b) => a.day > b.day ? 1 : -1)
    
    let route = ''
    
    let until = false
    
    for(let i = 0; i < hari.length; i++){
        if(i === 0){
            route+= hari[i].name
        } else {
            const before = (hari[i-1].day + 1)
            const after  = (hari[i+1] ? hari[i+1].day - 1 : 0)
            if(hari[i].day === before && hari[i].day === after){
                route+= until ? '' : ' - '
                until = true
            } else {
                route+= `${until ? '' : ', '}${hari[i].name}`
                until = false
            }
        }
    }
    
    return route
}

let hari1 = [
    {day:2, name:'tue'},
    {day:1, name:'mon'},
    {day:5, name:'fri'},
    {day:6, name:'sat'},
    {day:7, name:'sun'}
]

let hari2 = [
    {day:1, name:'mon'},
    {day:3, name:'wed'},
    {day:4, name:'thu'},
    {day:5, name:'fri'},
    {day:7, name:'sun'}
]

let hari3 = [
    {day:1, name:'mon'},
    {day:3, name:'wed'},
    {day:4, name:'thu'},
    {day:5, name:'fri'},
    {day:6, name:'sat'},
    {day:7, name:'sun'}
]



console.log(renderDay(hari1))
console.log(renderDay(hari2))
console.log(renderDay(hari3))
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement