繁体   English   中英

将子数组数据从索引转置为关联

[英]Transpose subarray data from indexed to associative

我正在制作一个 API 来获取一些数据。 我的 API 给出了 object 数据,就像给定的一样,给定 object 我想在 ZA8CFDE6331BD59EB266Z6F8911CB4 中格式化一些数据:

{
  "data": [
    {
      "productId": 55,
      "productTitle": "Test product",
      "variation": {
        "Color": "Red",
        "Size": "XS",
        "din": "10190537",
        "product_id": 55,
        "name": [
          "Color",
          "Size"
        ],
        "value": [
          "Red",
          "XS"
        ]
      },
      "din": "10190537",
      "markets": [
        {
          "id": 11,
          "name": "paytmmall",
          "displayName": "PayTm Mall",
          "identifierName": "Product_Id"
        }
      ]
    }
  ]
}

在这个 object 我想要给定的数据

 {
  "data": [
    {
      "productId": 55,
      "productTitle": "this is test from hariom",
      "variation": {
        "Color": "Red",
        "Size": "XS",
        "din": "10190537",
        "product_id": 55,
        "variationTypes": [
          {
            "name": "Color",
            "value": "Red"
          },
          {
            "name": "Size",
            "value": "XS"
          }
        ],
        
      },
      "din": "10190537",
      "markets": [
        {
          "id": 11,
          "name": "paytmmall",
          "displayName": "PayTm Mall",
          "identifierName": "Product_Id"
        }
      ]
    }
  ]
}

这是我的 Controller 名称

public function MarketMapping(Request $request)
    {
        $sellerId =  Auth::guard('seller-api')->user();
        $page = $request->has('pageNumber') ? $request->get('pageNumber') : 1;
        $limit = $request->has('perPage') ? $request->get('perPage') : 10;
        $variationFromInvTbl =  ProductInventory::select('Color', 'Size', 'din', 'product_id')->where('seller_id', $sellerId->id)->where('status', 'active')->limit($limit)->offset(($page - 1) * $limit)->get();
        $dataArray = array();
        foreach($variationFromInvTbl as $key => $varitionValue)
        {
            $prodtsFromLivetbl = ProductsLive::select('productTitle', 'product_id')->where('product_id', $varitionValue->product_id)->get();
            foreach ($prodtsFromLivetbl as $key => $value)
            {
                $marketChannelData = DB::table('market_channels')
                                ->join('sellers_market_channels', 'market_channels.name', '=', 'sellers_market_channels.key')
                                //->join('market_product_mappings', 'market_channels.id', '=', 'market_product_mappings.market_id')
                                ->select('market_channels.id','market_channels.name', 'market_channels.displayName','market_channels.identifierName') //'market_product_mappings.identifierValue'
                                ->where('sellers_market_channels.seller_id', $sellerId->id)
                                ->where('sellers_market_channels.value', 1)
                                ->get();
                $maketProductMap = MarketProductMapping::where('seller_id', $sellerId->id)->where('product_id', $varitionValue->product_id)->where('din', $varitionValue->din)->pluck('identifierValue');
                if (count($maketProductMap))
                {
                    $marketChannelData[$key]->value = $maketProductMap[0];
                }
                $varitionValue['name']= array_keys($varitionValue->only(['Color', 'Size']));
                $varitionValue['value'] = array_values($varitionValue->only(['Color', 'Size']));
                    $dataObject = ((object)[
                    "productId"     => $value->product_id,
                    "productTitle"  => $value->productTitle,
                    "variation"     => $varitionValue,
                    "din"           => $varitionValue['din'],
                    "markets"       => $marketChannelData
                ]);
                array_push($dataArray,$dataObject);
            }
        }
        if($variationFromInvTbl)
        {
            $response['success']        = true;
            $response["page"]           = $page;
            $response["itemPerPage"]    = $limit;
            $response["totalRecords"]   = $this->CountMarketMapping($page, $limit, $sellerId->id);
            $response['data']           = $dataArray;
            return response()->json($response, 200);
        }else{
            $response['success'] =  false;
            $response['data']    =  $prodtsFromLivetbl;
            return response()->json($response, 409);
        }
    }

您正在使用 laravel 的only()方法,它返回一个关联数组。

您希望将每个键值对转换为包含两个关联元素的子数组——原始键将是name元素的值,原始值将是value元素的值。

通过将原始数组键和数组值传递给array_map() ,您可以同步迭代它们。

compact()是一个完美的原生 function 从迭代参数创建所需的关联子数组。

代码:(演示

$variations = $varitionValue->only(['Color', 'Size']);

$dataObject = (object)[
    // ... your other data
    'variations' => array_map(
        function($name, $value) {
            return compact(['name', 'value']);
        },
        array_keys($variations),
        $variations
    ),
    // ...your other data
];

var_export($dataObject);

Output:

(object) array(
   'variations' => 
  array (
    0 => 
    array (
      'name' => 'Color',
      'value' => 'Red',
    ),
    1 => 
    array (
      'name' => 'Size',
      'value' => 'XS',
    ),
  ),
)

这个脚本会帮助你

<?php

$data = [
    "variation" => [
        [
            "Color"      => "Red",
            "Size"       => "XS",
            "din"        => "10190537",
            "product_id" => 55,
            "name" => [
                "0" => "Color",
                "1" => "Size"
            ],
            "value" => [
                "0" => "Red",
                "1" => "XS"
            ]
        ]
    ]
];

for ($i=0; $i < count($data["variation"]); $i++) { 
    $data["variation"][$i]["data"]["name"] = $data["variation"][$i]["name"];
    $data["variation"][$i]["data"]["value"] = $data["variation"][$i]["value"];

    unset($data["variation"][$i]["name"]);
    unset($data["variation"][$i]["value"]);
}

print_r($data);

output

Array
(
    [variation] => Array
        (
            [0] => Array
                (
                    [Color] => Red
                    [Size] => XS
                    [din] => 10190537
                    [product_id] => 55
                    [data] => Array
                        (
                            [name] => Array
                                (
                                    [0] => Color
                                    [1] => Size
                                )

                            [value] => Array
                                (
                                    [0] => Red
                                    [1] => XS
                                )
                        )
                )
        )
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM