Search code examples
phplaravellaravel-5transpose

Transpose subarray data from indexed to associative


I'm making an API for getting some data. My API gives object data like given, given object I wanted to format some data inside object:

{
  "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"
        }
      ]
    }
  ]
}

In this object I want data like given

 {
  "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"
        }
      ]
    }
  ]
}

Here Is my Controller Name

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);
        }
    }

Solution

  • You are using laravel's only() method which returns an associative array.

    You wish to convert each key-value pair into a subarray containing two associative elements -- the original key will be the value of the name element and the original value will be the value of the value element.

    By passing the original array keys and array values into array_map(), you can iterate them both synchronously.

    compact() is a perfect native function to create the desired associative subarrays from the iterated parameters.

    Code: (Demo)

    $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',
        ),
      ),
    )