Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Łukasz Czuliński
Łukasz Czuliński
8,646 Points

Restructuring nested array.

Hi everyone. I've been at this a while and my brain is starting to hurt.

Basically, I have an array like this:

$pricing = [
   'item' => [
        0 => 'consultation',
        1 => 'design'
    ], 
    'description' => [
        0 => '',
        1 => 'main conception'
    ],
    'price' => [
        0 => '300',
        1 => '800'
    ]
]

Which I want to turn into something like this:

$items = [
   0 => [
        'item' => 'consultation',
        'description' => '',
        'item_price' => '300'   
    ],
    1 => [
        'item' => 'design',
        'description' => 'main conception',
        'item_price' => '800'
    ]
]

I'm after something very reusable since the amount of inputs are dynamic and user-controlled. My most recent failed attempt was this:

$newArray = [];

for($i = 0; $i < count($input['item']); $i++)
{
    foreach($input as $key => $row)
    {
        $newArray[$i] = [$key => $row[$i]];
    }
}

This created the two indexed arrays that I want, but only returned a single key => value pair.

array (size=2)
  0 => 
    array (size=1)
      'item_price' => string '300' (length=1)
  1 => 
    array (size=1)
      'item_price' => string '800' (length=1)

What am I missing here?

1 Answer

Łukasz Czuliński
Łukasz Czuliński
8,646 Points

Ended up figuring it out. Some renaming of the foreach variables made it easier to picture.

$newArray = [];

foreach ($input as $field => $indexes) {
    for ($i = 0; $i < count($indexes); $i++) {
        $newArray[$i][$field] = $indexes[$i];
    }
}

return $newArray;

This gives the desired array.