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

Time:11-27

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

CodePudding user response:

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();

CodePudding user response:

You must move this line

$koleksi = [];

outside of your loop, otherwise on each iteration you reset it back to empty ([]) so at the end of the loop it will be holding only last element.

$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}"});
}

I also wonder what the point of so complex variable name creation. array_push() will push the value anyway so there's no point. Even more, there's no point for array_push() either:

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

Finally, I'd replace 'Suara '.$i of your where() with "Suara {$i}" simply for better readability.

  • Related