Как назначить имя для родительского массива в массиве в PHP? - PullRequest
0 голосов
/ 10 октября 2019

У меня есть массив с именем $ 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
)

Ответы [ 3 ]

1 голос
/ 10 октября 2019

Следующее сработало для меня:

$a['test'] = $a[0];
unset($a[0]);

Вот результат массива до и после, разделенный новой строкой: Оригинал:

array (
  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,
    ),
  ),
)

Изменено:

array (
  'test' => 
  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,
    ),
  ),
)
0 голосов
/ 14 октября 2019

ОК .... поэтому большой проблемой было не создание массива. Было слияние ....

Это решило проблему: https://stackoverflow.com/a/6417137/5240406

array_unshift () создает новые ключи, если они числовые или нет, , как упоминалосьздесь

Вместо использования:

array_unshift($arr1, $arr2)

Я использовал:

$arr1 = $arr2 + $arr1;
0 голосов
/ 10 октября 2019

Здравствуйте, вы можете просто скопировать значение в новый ключ:

$dados_cotacao_array['Products'] = $array_produtos[0];
...