【发布时间】:2019-10-10 16:32:08
【问题描述】:
我有一个名为 $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
)
【问题讨论】:
-
你的例子是
$array_products[0][0],提供更多代码。 -
我的例子有:
$array_products[0]是父级,$array_products[0][0]是第一个孩子,最后$array_products[0][1]是最后一个孩子。我的愿望是将$array_products[0]重命名为$array_products[Products],以便拥有:$array_products[Products][0]和$array_products[Products][1],我可以使用array_unshift($first_array, $array_products[Products]);
标签: php arrays multidimensional-array