Skip to main content

Accessing data in an associative array in CodeIgniter 3

I'm using CodeIgniter 3 and I'm passing an associative array from the controller to the view. In the view I'm trying to render a chart using ChartJS so I need to get the data of 0th and 1st indexes separately. {"label":["A+","AB-","B+","B-","O+"],"data":["6","2","5","2","3"]} is the associative array I'm passing. Below is the code in the controller.

public function bloodTypesChart()
    {
        $totalPackets = $this->db->count_all_results();

        $chartData = [];
        $blood_types = $this->db->query("SELECT (BloodType) as blood_type FROM packets WHERE (isAvailable) = '1' GROUP BY blood_type")->result_array();

        $record = $this->db->from('packets')
            ->select('count(PacketID) count, BloodType blood_type')
            ->group_by('blood_type')
            ->get()
            ->result_array();

        foreach ($record as $row) {
            $chartData['label'][] = $row['blood_type'];
            $chartData['data'][] = $row['count'];
        }
        $chartData['chart_data'] = json_encode($chartData);
        $this->load->view('insight', $chartData);
    }

I need to pass data in the label and data indexes separately to the ChartJS function. How can I do that in the view?

View

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css"/>
    <link rel="stylesheet" type="text/css" href="<?php echo base_url('assests/styles/table.css'); ?>">
    <title>Kegalle Blood Bank - Blood Types Insight</title>
</head>
<body style="margin-bottom: 50px">
<?php include_once 'navbars/navbar2.php' ?>

<?php
if (!($this->session->userdata('isStaffLoggedIn'))) {
    redirect('home/login');
}
?>


<div class="container">
    <div class="row">
        <div class="col-md-12 text-center mt-5">
            <h1>Insight</h1>
        </div>
        <div class="row text-center m-5">
            <div class="col-md-6">
                <div class="card border-info mx-sm-1 p-3 shadow-lg">
                    <div class="card border-danger shadow text-danger p-3 my-card"><span class="fa fa-heart"
                                                                                         aria-hidden="true"></span>
                    </div>
                    <div class="text-danger text-center mt-3"><h4>Total Donors</h4></div>
                    <div class="text-danger text-center mt-2"><h1><?php echo $donorcount; ?></h1></div>

                </div>
            </div>
            <div class="col-md-6">
                <div class="card border-success mx-sm-1 p-3 shadow-lg">
                    <div class="card border-success shadow text-success p-3 my-card"><span class="fa fa-eye"
                                                                                           aria-hidden="true"></span>
                    </div>
                    <div class="text-success text-center mt-3"><h4>Total Available Packets</h4></div>
                    <div class="text-success text-center mt-2"><h1><?php echo $packetcount; ?></h1></div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="chart-container container">
    <div class="bar-chart-container">
        <canvas id="bar-chart" style="background: #fff"></canvas>
    </div>
</div>

<?php include_once 'footer/footer.php' ?>
</body>

<script>
    new Chart(document.getElementById("bar-chart"), {
        type: 'bar',
        data: {
            labels: <?php echo $label?>,
            datasets: [
                {
                    label: "Population (millions)",
                    backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
                    data: <?php echo $data?>
                }
            ]
        },
        options: {
            legend: { display: false },
            title: {
                display: true,
                text: 'Predicted world population (millions) in 2050'
            }
        }
    });
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.6.2/dist/chart.min.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>

</html>


source https://stackoverflow.com/questions/70418802/accessing-data-in-an-associative-array-in-codeigniter-3

Comments

Popular posts from this blog

Confusion between commands.Bot and discord.Client | Which one should I use?

Whenever you look at YouTube tutorials or code from this website there is a real variation. Some developers use client = discord.Client(intents=intents) while the others use bot = commands.Bot(command_prefix="something", intents=intents) . Now I know slightly about the difference but I get errors from different places from my code when I use either of them and its confusing. Especially since there has a few changes over the years in discord.py it is hard to find the real difference. I tried sticking to discord.Client then I found that there are more features in commands.Bot . Then I found errors when using commands.Bot . An example of this is: When I try to use commands.Bot client = commands.Bot(command_prefix=">",intents=intents) async def load(): for filename in os.listdir("./Cogs"): if filename.endswith(".py"): client.load_extension(f"Cogs.{filename[:-3]}") The above doesnt giveany response from my Cogs ...

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...