Emkrypted
Emkrypted

Reputation: 67

Fill an multidimensional array with a foreach

I need to make an array like this

   $preferenceData = [
            'items' => [
                [
                    'id' => 1,
                    'title' => 'Recarga de Créditos',
                    'description' => 'Recarga de Créditos para Negocioson.com',
                    'quantity' => 1,
                    'currency_id' => 'ARS',
                    'unit_price' => $amount
                ]
            ]
        ];

But I need to create it with a foreach

 foreach ($items as $item) {

}

I tried this:

$data[0]['items'][0]['id'] = 1;

BUT the results are not the same:

This is mine:

Array ( [0] => Array ( [items] => Array ( [0] => Array ( [id] => 1 ) ) ) ) 

This is the preference one:

Array ( [items] => Array ( [0] => Array ( [id] => 1 ) ) )

I add a [0] how can I delete it?

Thanks

Upvotes: 0

Views: 30

Answers (2)

aljx0409
aljx0409

Reputation: 242

You can do something like:

$data = [];
foreach ($items as $item) {
    $data['items'][] = [
        'id' => $item['id'],
        'title' => $item['title'],
        ...
    ];
}

Upvotes: 0

Barmar
Barmar

Reputation: 780688

You shouldn't use $data[0]. The top-level array is an associative array, not numeric.

$data['items'][0] = [
    'id' => 1,
    'title' => 'Recarga de Créditos',
    'description' => 'Recarga de Créditos para Negocioson.com',
    'quantity' => 1,
    'currency_id' => 'ARS',
    'unit_price' => $amount
];

Upvotes: 1

Related Questions