I have an array called $array_products, this is how it looks right now in print_r:
[0] => Array
(
[0] => Array
(
[weight] => 297
[height] => 40
[width] => 60
[lenght] => 540
[price] => 5975
)
[1] => Array
(
[weight] => 75
[height] => 40
[width] => 60
[lenght] => 222
[price] => 3351
)
)
How do I make the first parent array have a name instead of one? This is what I'm trying to achieve (keeping the multidimensional structure):
[Products] => Array
(
[0] => Array
(
[weight] => 297
[height] => 40
[width] => 60
[lenght] => 540
[price] => 5975
)
[1] => Array
(
[weight] => 75
[height] => 40
[width] => 60
[lenght] => 222
[price] => 3351
)
)
Because I will use array_unshift to make this array in the top of another array. I don't know if array_map is what I'm looking for, but I haven't found a way to do that.
--Edit
By using:
$array_products['Products'] = $array_products[0];
unset($array_products[0])
As suggested by @freeek this is what I get:
(
[1] => Array
(
[weight] => 75
[height] => 40
[width] => 60
[lenght] => 222
[price] => 3351
)
[Products] => Array
(
[weight] => 297
[height] => 40
[width] => 60
[lenght] => 540
[price] => 5975
)
)
It basically removed the parent array moving the childs to the top, and renamed the first array 0 to Products. =/
--- This is the actual PHP (shortened):
// First array is created here:
foreach ( $package['contents'] as $item_id => $values ) {
$product = $values['data'];
$qty = $values['quantity'];
$shippingItem = new stdClass();
if ( $qty > 0 && $product->needs_shipping() ) {
$shippingItem->peso = ceil($_weight);
$shippingItem->altura = ceil($_height);
$shippingItem->largura = ceil($_width);
$shippingItem->comprimento = ceil($_length);
$shippingItem->valor = ceil($product->get_price());
....
}
//This is the second part of the array, outside the first one:
$dados_cotacao_array = array (
'Origem' => array (
'logradouro' => "",
'numero' => "",
'complemento' => "",
'bairro' => "",
'referencia' => "",
'cep' => $cep_origem
),
'Destino' => array (
'logradouro' => "",
'numero' => "",
'complemento' => "",
'bairro' => "",
'referencia' => "",
'cep' => $cep_destino
),
'Token' => $this->token
);
// Then I merge the first array with the second one
array_unshift($dados_cotacao_array, $array_produtos);
// And encode in json to send everything via cURL Post to an external API
$dados_cotacao_json = json_encode($dados_cotacao_array);
In the end this is what I'm trying to achieve:
Array
(
[Products] => Array
(
[0] => Array
(
[weight] => 297
[height] => 40
[width] => 60
[lenght] => 540
[price] => 5975
)
[1] => Array
(
[weight] => 75
[height] => 40
[width] => 60
[lenght] => 222
[price] => 3351
)
)
[Origem] => Array
(
[logradouro] =>
[numero] =>
[complemento] =>
[bairro] =>
[referencia] =>
[cep] => 1234567
)
[Destino] => Array
(
[logradouro] =>
[numero] =>
[complemento] =>
[bairro] =>
[referencia] =>
[cep] => 1234567
)
[Token] => token
)