Skip to content
Advertisement

how to enter data into an array with a loop. laravel

I want to insert data from the database into an array that can be increased in number. So maybe you can use a loop but the data is stacked, not added and returns the last data

i am trying to use for with $i++ to generate $variable.$i. that’s what I was expecting but I don’t understand how to run it

for ($i = 1; $i < $sumjnssuara; $i++){
            $koleksi = [];
            ${"suwara{$i}"} = DB::table('suara')->where('suara','Suara '.$i)->pluck('jml_suara')->sum();
            array_push($koleksi, ${"suwara{$i}"});
        }

the problem might be solved if $suwara1++ and makes the $koleksi array grow

Advertisement

Answer

The problem is that you recreate the array at each iteration. you need to create it outside the loop:

$koleksi = [];
for ($i = 1; $i < $sumjnssuara; $i++){
    ${"suwara{$i}"} = DB::table('suara')->where('suara','Suara '.$i)->pluck('jml_suara')->sum();
    array_push($koleksi, ${"suwara{$i}"});
}

Then I would get rid of creating variables with a different name in each iteration. That doesn’t make sense:

$koleksi = [];
for ($i = 1; $i < $sumjnssuara; $i++){
    $suwara = DB::table('suara')->where('suara','Suara '.$i)->pluck('jml_suara')->sum();
    $koleksi[] = $suwara;
}

And finally all of this can be implemented with a single query in the database:

$koleksi = DB::table('suara')
    ->groupBy('suara')
    ->pluck(DB::raw('sum(jml_suara) as sum'), 'suara')
    ->toArray();
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement