简体   繁体   中英

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

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
];

You can do something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM