Randy
Randy

Reputation: 11

Looping a Multi Dimensional Array

I encountered this kind of array in my tasks. It's a multi dimensional array. In the form, I have this,

particular[particular][]
particular[percentage][]
particular[remarks][]

So what I'm doing is, I'm getting request

$inputs = $request->all();

this returns

 array:3 [▼
    "particular" => array:3 [▶]
    "percentage" => array:3 [▶]
    "remarks" => array:3 [▶]
 ]

inside, each of them have

 array:3 [▼
     "particular" => array:3 [▼
         0 => "11"
         1 => "22"
         2 => "33"
     ] 
     "percentage" => array:3 [▼
         0 => "11"
         1 => "22"
         2 => "33"
     ]
     "remarks" => array:3 [▼
         0 => "na1"
         1 => "na2"
         2 => "na3"
      ]
 ]

I tried looping it

foreach ($inputs as $input) {
     dd($input);
}

but I only get the first one "particular" => array:3 [▶]

What I'm after is, I need to save those value in database

 $particular = new Particular;
 $particular->particular = particular;
 $particular->percentage = percentage;
 $particular->remarks = remarks;
 $particular->save();

Upvotes: 0

Views: 61

Answers (2)

Randy
Randy

Reputation: 11

I managed to find a solution. I don't know if this is the proper, but for now atleast it work for me.

    $array1 = $request->particular;
    $array2 = $request->percentage;
    $array3 = $request->remarks;

    $merge = [$array1, $array2, $array3];

    foreach ($merge[0] as $key => $value) {
        $particular = new Particular;
        $particular->particular = $merge[0][$key];
        foreach ($merge[1] as $x => $y) {
            $particular->percentage = $merge[1][$key];

        }
        foreach ($merge[2] as $i => $d) {
            $particular->remarks = $merge[2][$key];

        }
        $particular->report_id = $report->id;
        $particular->save();
    }

Upvotes: -1

u_mulder
u_mulder

Reputation: 54841

dd means "dump and DIE" so your script dies on first iteration.

You can:

$particular = new Particular;
$particular->particular = $inputs['particular'];
$particular->percentage = $inputs['percentage'];
$particular->remarks = $inputs['remarks'];
$particular->save();

Also, if you need to just dump something - there's a dump function (surprise!):

foreach ($inputs as $input) {
    dump($input);
}

Upvotes: 3

Related Questions