ctf0
ctf0

Reputation: 7579

multi level dimensional array in php

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 :(.

Upvotes: 2

Views: 55

Answers (1)

Gavriel
Gavriel

Reputation: 19237

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']
     ]);
}

Upvotes: 2

Related Questions