在 php 中的现有数组中添加数组

Add array in exiting array in php

我有一个json。首先我必须解码然后在 json.

的特定键上添加循环
public function saveRecode() {
    $json ='{"productID":"1","productPrice":"5585.00","productDetails":{"productImage":"https:\/\/development.modeconfigurator.com\/eCommerce\/backdrop.jpg","TABLE TOP":"COPPER DISTRESSED","TABLE FRAME":"RAL 5024 PASTEL BLUE"},"_":"1583172411557"}';

    $jsonDecode = json_decode($json, true);
    foreach ($jsonDecode["productDetails"] as $key => $value) {
        $options = [
            '0' => [
                'sort_order' => '1',
                'title' => $key,
                'price_type' => 'fixed',
                'price' => '',
                'type' => 'drop_down',
                'is_require' => '0',
                'values' => [
                    '0' =>[
                        'title' => $value,
                        'price' => '',
                        'price_type' => 'fixed',
                        'sku' => '',
                        'sort_order' => '0',
                        'is_delete' => '0',
                        ]
                    ]
                ]
            ];
    }
    foreach ($options as $arrayOption) {
        $this->_logger->debug("enter in opt ");
        $this->_logger->info(print_r($arrayOption,true));
        $option = $this->_options
            ->setProductId($_product->getId())
            ->setStoreId($_product->getStoreId())
            ->addData($arrayOption);
        $option->save();
        $_product->addOption($option);
    }
}

在数据库中只保存最后一次重新编码。但是我想保存所有参数请循环。

您每次通过循环替换 $options,而不是向其添加新元素。应该是:

$options = [];
foreach ($jsonDecode["productDetails"] as $key => $value) {
    $options[] = [
        'sort_order' => '1',
        'title' => $key,
        'price_type' => 'fixed',
        'price' => '',
        'type' => 'drop_down',
        'is_require' => '0',
        'values' => [
            '0' =>[
                'title' => $value,
                'price' => '',
                'price_type' => 'fixed',
                'sku' => '',
                'sort_order' => '0',
                'is_delete' => '0',
            ]
        ]
    ];
}