2

i've been trying to figure out how to make a foreach loop on a multi-dimesial array but sadly with no luck, i have the below array

$levels = [
        'A' => [
            'xx' => null,
            'yy' => 0
        ],
        'B' => [
            'xx' => 1,
            'yy' => 100
        ],
        'C' => [
            'xx' => 3,
            'yy' => 250
        ],
        'D' => [
            'xx' => 6,
            'yy' => 500
        ]
    ];

the xx & yy are columns in a table and am simply trying to assign some values to both of them like so

foreach ($levels as $level => $info) {
    foreach ($info as $key => $value) {
        Level::create([
             'name' => $level,
             'xx'   => $value,
             'yy'   => $value
         ]);
      }
  }

but this doesnt work and it creates a duplicated entries :(.

4
  • The part of code you showed seems quite correct. The problem must be in your create() method, so please show it. Commented Jan 29, 2016 at 0:57
  • 2
    actually you don't need another depth of foreach, in the first foreach just use $info['xx'] and $info['yy'] Commented Jan 29, 2016 at 0:57
  • @Ghost r u kidding me, its that easy O.o, many many thanx for your quick response :) Commented Jan 29, 2016 at 1:02
  • @ctf0 yes that's why you got the duplicates, you're looping under the unneeded depth, the first foreach is just all you need, glad this helped Commented Jan 29, 2016 at 1:04

1 Answer 1

2

You don't need the inner foreach. You can reach xx, yy from $info:

foreach ($levels as $level => $info) {
    Level::create([
         'name' => $level,
         'xx'   => $info['xx'],
         'yy'   => $info['yy']
     ]);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.