interstellar
interstellar

Reputation: 25

How do i do foreach loop in array inside an array in CakePHP?

I have a variable for eg: $Foods, which stores arrays like:

array(
    'Fruit' => 'Banana',
    'cake' => array(
        (int) 0 => '10',
        (int) 1 => '11',
        (int) 2 => '12'
    )
)

I want to have this like :

array(
    'Fruit' => 'Banana',
    'cake' =>  '10'
)
array(
    'Fruit' => 'Banana',
    'cake' =>  '11'
)
 array(
    'Fruit' => 'Banana',
    'cake' =>  '12'
)

How can I achieve this?

Upvotes: 0

Views: 956

Answers (1)

msk
msk

Reputation: 481

try this code

<?php
        $Foods = array('Fruit' => 'Banana', 'cake' => array('10','11','12'));

        $newFoods = array();
        foreach($Foods['cake'] as $key => $val): 
            $newFoods[$key]['Fruit'] =  $Foods['Fruit'];
            $newFoods[$key]['cake'] =  $val;
        endforeach;

        print_r($newFoods);
    ?>

output will be

Array
(
    [0] => Array
        (
            [Fruit] => Banana
            [cake] => 10
        )

    [1] => Array
        (
            [Fruit] => Banana
            [cake] => 11
        )

    [2] => Array
        (
            [Fruit] => Banana
            [cake] => 12
        )

)

Upvotes: 2

Related Questions