简体   繁体   中英

Looping through database with array and save data into variable Laravel

I have an array which stores vehicles models. And i have a database table with all vehicles compatibility.

I need to through database table and find all vehicles that in array. Actually I did it and I can loop through the database with array and get all necessary information about vehicles. But my problem is I cannot save the data to the variable. For some reason it's empty.

But if i just want to display data with echo function I can actually do this.

Here is my code:

$listing = str_replace( ", ", ",", $model );

        $modle_arrs = explode(',', $listing);

        foreach($modle_arrs as $modle_arr){

            $e_compts = EbayCompatrbilityCategorie::all()->where('model', $modle_arr);

            $compt_val = "{";
                foreach ($e_compts as $e_compt) {
                    $compt_val .= "[" . $e_compt['year'] . "]";
                    $compt_val .= "[" . $e_compt['model'] . "]";

                    echo "[" . $e_compt['year'] . "]";
                    echo "[" . $e_compt['model'] . "]";
                }
            $compt_val .= "}";

        }

        dd($compt_val);

And here is output in browser: 在此处输入图片说明

How can I store data into variable in this situation?

You are overwriting $compt_val on every iteration. If the query comes back as empty on the last iteration, $compt_val will be empty. Try keeping all the values in an array:

$listing = str_replace( ", ", ",", $model );

$modle_arrs = explode(',', $listing);
$compt_val_all = [];
foreach($modle_arrs as $modle_arr){

    $e_compts = EbayCompatrbilityCategorie::all()->where('model', $modle_arr);

    $compt_val = "{";
        foreach ($e_compts as $e_compt) {
            $compt_val .= "[" . $e_compt['year'] . "]";
            $compt_val .= "[" . $e_compt['model'] . "]";

            echo "[" . $e_compt['year'] . "]";
            echo "[" . $e_compt['model'] . "]";
        }
    $compt_val .= "}";
    $compt_val_all[] = $compt_val;
}

dd($compt_val_all);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM