简体   繁体   中英

Multidimensional array loop php

New to programming so please explain as simply as possible. I have an array as $inputs. That array has rows as row0, row1 and on. Each row has key value pairs such as name='shay', age='23' and a few other things. I need to put those values in a database, but I can't figure out how to get to them and the examples I find go right over my head. I have made a loop with

for ($i = 0, $nums = count($inputs); $i < $nums; $i++)

But once inside of that loop I am lost as to what comes next. Please help.

The array looks as follows:

    $inputs =array ( 
         'row' => array ( 
                        0 => array ( 'id' => '2869', 'name' => 'shay', 'age' => '23',), 
                        1 => array ( 'id' => '2868', 'name' => 'Tim', 'age' => '30',), 

What I need to do is go through and do an insert with $name, $age etc. So I created the for loop, but I have no idea what to do inside of it to get the values of name and age etc for each row. I know how to insert them, it's just getting the values out of the array.

When I use

foreach ($inputs as $key => $row)

I can then do

dd($row['0']); 

And return the contents of a row that I would then like to put in my query. I just don't really understand how to go from the dd() to actually accessing the values for each rows in a way that I could insert them.

You can loop over that data like this:

foreach($inputs as $key => $row) {
    echo "row $key:\n"; 
    foreach ($row as $person) {
        echo " - " . $person['name'], " is ", $person['age'], " old.\n";
    }
}

See it run on eval.in

Output based on the input you provided:

row row:
- shay is 23 old.
- Tim is 30 old.

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