У меня есть массив с именем $ array_products, вот как он выглядит прямо сейчас в 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
)
)
Как сделать так, чтобы первый родительский массив имел имя вместо одного? Вот что я пытаюсь достичь (сохраняя многомерную структуру):
[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
)
)
Потому что я буду использовать array_unshift, чтобы сделать этот массив в верхней части другого массива. Я не знаю, является ли array_map тем, что я ищу, но я не нашел способа сделать это.
- Редактировать
Используя:
$array_products['Products'] = $array_products[0];
unset($array_products[0])
Как подсказывает @freeek, вот что я получаю:
(
[1] => Array
(
[weight] => 75
[height] => 40
[width] => 60
[lenght] => 222
[price] => 3351
)
[Products] => Array
(
[weight] => 297
[height] => 40
[width] => 60
[lenght] => 540
[price] => 5975
)
)
Он в основном удалил родительский массив, переместив дочерние элементы наверх, и переименовал первый массив 0 в Products. = /
--- Это фактический PHP (сокращенно):
// 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);
В конце концов, это то, чего я пытаюсь достичь:
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
)