DEV Community

1batu
1batu

Posted on

Value-based data assignment from json.

The scenario is as follows, the student takes the exam and according to the exam result, the system defines it to the training package. To do this, we define the score and package number in the database beforehand.

The json structure we saved in the database is as follows.

[
{"score":"-35-39","package":"a1","price":"7500"},
{"score":"40-49","package":"a2","price":"6000"},
{"score":"50-59","package":"a3","price":"4500"},
{"score":"60-69","package":"a4","price":"3000"},
{"score":"70-79","package":"a5","price":"1500"},
{"score":"80-89","package":"a6","price":"free"},
{"score":"90-100","package":"a7","price":"free"}
]
Enter fullscreen mode Exit fullscreen mode

The first thing we need is a variable where we will specify the student's score.

$point // Student score

$points = json_decode(getSiteOptions('sbsJson'), true); 
// It is getting the above mentioned json data from my setting.
$point = 45; // Student score
Enter fullscreen mode Exit fullscreen mode
$data = [];
$points = json_decode(getSiteOptions('sbsJson'), true);
$point = 45;

foreach ($points as $a) {
        $parcala = explode('-', $a['score']);
        if ($parcala[0] !== "") {
            $parcala[0] = ((int) trim($parcala[0])) === 0 ? -1 : $parcala[0];
            if ($parcala[0] < $point && $point <= $parcala[1]) 
            {
                $data = [
                    'sbs_package' => $a['package'],
                    'sbs_price' => $a['price']
                ];
            }
        } else {
            if ($point <= $parcala[1]) {
               $data = [
                    'sbs_package' => $a['package'],
                    'sbs_price' => $a['price']
                ];
            }
        }
}

return $data;
Enter fullscreen mode Exit fullscreen mode

It's working pretty well for me now, I'm waiting for your comments if we can fix it with a shorter code.. :)

Top comments (0)