Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to dynamically extract keys from the request data to construct sample json response

how to create associative array from dynamic request

<?php

// Assuming you have a form with input fields named 'key1', 'key2', 'key3', etc.
// and you want to retrieve values dynamically from the request

// Get all input values from the request
$inputValues = request()->all();

// Initialize an empty associative array
$associativeArray = [];

// Loop through the input values and build the associative array
foreach ($inputValues as $key => $value) {
    $associativeArray[$key] = $value;
}

// Output the associative array
print_r($associativeArray);
Enter fullscreen mode Exit fullscreen mode

Add new key value pair in above


// Add a new key-value pair
$newKey = 'key4';
$newValue = 'value4';

$associativeArray[$newKey] = $newValue;
print_r($associativeArray);

Enter fullscreen mode Exit fullscreen mode

my request data is

take specific data from associative array based on suffix and put in array
retrived array put inside response

[2024-01-05 07:46:06] local.INFO: array (
  '_token' => 'JEQba4vUNZ5LP1Jz7eaI9JAwblbOAf7S8EO6i14C',
  'face_price' => '24',
  'youtube_price' => '69',
  'admin_id' => '26',
  'slug' => 'admins',
  'influencer_email' => 'admins@gmail.com',
  'influencer_admin_id' => NULL,
  'org_name' => NULL,
  'admin_email' => 'rakeshdev.cotocus@gmail.com',
  'user_name' => 'rakeshdev',
  'slug_id' => NULL,
)  
Enter fullscreen mode Exit fullscreen mode

I want to extract request data where suffix is _price and user_name and slug and put in json response

step1: extract request key and put inside array $priceData

  $priceData = [];
            foreach ($request->all() as $key => $value) {
                if (strpos($key, '_price') !== false) {
                    $priceData[$key] = $value;
                }
            }
Enter fullscreen mode Exit fullscreen mode

step2: next step to construct json response

                        return response()->json([
                            'message' => "task disapprove successfully", 
                            'success' => true,
                            'prices' => $priceData, 
                            'influencer' =>$request->slug,
                            'publisher' =>$request->user_name,     
                        ]);
Enter fullscreen mode Exit fullscreen mode

output

{
    "message": "Task disapproved successfully",
    "success": true,
    "prices": {
        "face_price": "24",
        "youtube_price": "69"
    },
    "influencer": "sample-influencer",
    "publisher": "sample-publisher"
}
Enter fullscreen mode Exit fullscreen mode

Another way

WAP to get associtive array of single row from db
wap to to create array of object in json for single associative array

 $myaddcarts=addcart::where('influencer_admin_id',$data->user_id)->first();
                         Log::info($myaddcarts);

                         if ($myaddcarts) {
                             $paymentsArray = $myaddcarts->toArray();                         
                             foreach ($paymentsArray as $key => $value) {                              
                                 if (strpos($key, '_price') !== false && $value !== null) {
                                     $socialSite = str_replace('_price', '', $key);                 
                                $priceData['prices'][] = ['social_site' => $socialSite, 'price' => $value];
                                Log::info('Price data:', $priceData['prices']);
                                        }
                                    }
                                }
                        return response()->json([
                            'message' => "task disapprove successfully", 
                            'success' => true,
                            'prices' => $priceData, 
                            'influencer' =>$request->slug,
                            'publisher' =>$request->user_name,     
                        ]);
Enter fullscreen mode Exit fullscreen mode

json format

{
  "message": "task disapprove successfully",
  "success": true,
  "prices": {
    "prices": [
      {"social_site": "face", "price": 24},
      {"social_site": "youtube", "price": 69},
      // ... other social sites and prices
    ]
  },
  "influencer": "admins",
  "publisher": "rakeshdev"
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)