Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to handle dynamic data using key value pair in laravel

concept of key value pair
how to store static data key value pair in database
how to store dynamic data key value pair in database
how to display key value pair data in html
how to apply condition while iterating array of data
how to check specific value present or not in indexed arrays
how to update in exisiting json data in table

concept of key value pair

$data = ['name' => 'John', 'age' => 30, 'city' => 'New York'];
Enter fullscreen mode Exit fullscreen mode
foreach ($data as $key => $value) {
    echo "Key: $key, Value: $value\n";
}
Enter fullscreen mode Exit fullscreen mode

Output:

Key: name, Value: John
Key: age, Value: 30
Key: city, Value: New York
Enter fullscreen mode Exit fullscreen mode

how to store static data key value pair in database

update(['addcarts' => "$admins_email:yes"])

Database Setup:

Open PHPMyAdmin and create a new database for your Laravel project or use an existing one.
Note the database credentials (database name, username, and password) as you'll need them in your Laravel configuration.
Laravel Configuration:

In your Laravel project, open the .env file and configure the database connection settings by updating the following variables:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password
Enter fullscreen mode Exit fullscreen mode

Create a Migration:

Use Laravel's Artisan command-line tool to generate a migration for creating the table. Run the following command:

php artisan make:migration create_key_value_table
Enter fullscreen mode Exit fullscreen mode

Open the generated migration file in the database/migrations directory. In this example, it's something like create_key_value_table.php.

Define the table schema for your key-value pairs. For example:

public function up()
{
    Schema::create('key_value_pairs', function (Blueprint $table) {
        $table->id();
        $table->string('key')->unique();
        $table->text('value');
        $table->timestamps();
    });
}
Enter fullscreen mode Exit fullscreen mode

This migration creates a table called key_value_pairs with columns for key (string), value (text), and standard timestamp columns.

Run the Migration:

Execute the migration to create the table in the database:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Store Data as Key-Value Pairs:

In your Laravel application code, you can now store data as key-value pairs in the key_value_pairs table. For example:

use Illuminate\Support\Facades\DB;

// Insert a key-value pair into the database
DB::table('key_value_pairs')->insert([
    'key' => 'app_name',
    'value' => 'My Laravel App',
]);
Enter fullscreen mode Exit fullscreen mode

You can also update or retrieve key-value pairs as needed.

Access Data:

To retrieve data from the key_value_pairs table, you can use Laravel's Eloquent ORM or the query builder. For example:

use Illuminate\Support\Facades\DB;

// Retrieve the value associated with the 'app_name' key
$value = DB::table('key_value_pairs')
    ->where('key', 'app_name')
    ->value('value');
Enter fullscreen mode Exit fullscreen mode

Display Data:

You can then use the retrieved data in your Laravel application, such as displaying it in views or using it in your application's logic.

how to store dynamic data key value pair in database

To store data as key-value pairs that come dynamically with a request in a Laravel application using PHPMyAdmin, you can follow these steps:

Database Setup:

Open PHPMyAdmin and create a new database for your Laravel project or use an existing one.
Note the database credentials (database name, username, and password) as you'll need them in your Laravel configuration.
Laravel Configuration:

In your Laravel project, open the .env file and configure the database connection settings by updating the following variables:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password
Enter fullscreen mode Exit fullscreen mode

Create a Migration for Key-Value Storage:

Use Laravel's Artisan command-line tool to generate a migration for creating a table to store key-value pairs. Run the following command:

php artisan make:migration create_key_value_table
Enter fullscreen mode Exit fullscreen mode

Open the generated migration file in the database/migrations directory (e.g., create_key_value_table.php).

Define the table schema for key-value pairs. For example:

public function up()
{
    Schema::create('key_value_pairs', function (Blueprint $table) {
        $table->id();
        $table->string('key')->unique();
        $table->text('value');
        $table->timestamps();
    });
}
Enter fullscreen mode Exit fullscreen mode

This migration creates a table called key_value_pairs with columns for key (string), value (text), and standard timestamp columns.

Run the Migration:

Execute the migration to create the key_value_pairs table in the database:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

====================

 $addingprofile= DB::table("addprofiles")->where('id',$itemId)->update(['addcarts' => "$admins_email:yes"]);


Enter fullscreen mode Exit fullscreen mode

In phpmyadmin

Image description

in blade file
WAp to apply condition on single value consist of concatenation of string and special symbol

    @php
                        $parts = explode(':', $item->addcarts);
                        $valueAfterColon = isset($parts[1]) ? $parts[1] : null;
                          @endphp
                          @if (($parts[1] == 'yes') && (auth()->user()->email == $parts[0]))  

                            <button type="submit"  
                             class="btn btn-sm  btn-primary" style="position: relative;float:right">Added</button> 
                            @else
                            <button type="submit"  
                             class="btn btn-sm  btn-primary addToCartBtn" data-item-id="{{ $item->id }}"  style="position: relative;float:right">Add To Cart</button> 
                            @endif 
Enter fullscreen mode Exit fullscreen mode

output

Image description
another way

use Illuminate\Database\Eloquent\Model;

class YourModel extends Model
{
    protected $fillable = ['socialsite'];

    public function storeData()
    {
        // Data to be stored in JSON format
        $data = [
            'facebook' => 50,
            'twitter' => 30,
            'utube' => 80,
        ];

        // Encode the array into JSON format
        $jsonData = json_encode($data);

        // Store the data in the database
        YourModel::create([
            'socialsite' => $jsonData,
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

===============Practical Examples=========================
In controller function
insert data

  public function userActivateStore(Request $request)
    {
        $add_profile = new Addprofile();     
        $add_profile->profile_status = json_encode(['register' => 
           'yes']);
        $add_profile->slug = $slug;
        $add_profile->save(); 
        return view('org');

        }
Enter fullscreen mode Exit fullscreen mode

output in phpmyadmin

{"register":"yes","socialurl":"yes","price":"yes","describe":"yes","pic":"yes"}  
Enter fullscreen mode Exit fullscreen mode

update data

how to update in exisiting json data in table

Wap to update data in exisiting json

     // Retrieve the existing JSON data from the database
        $existingData = DB::table('addprofiles')
        ->where('user_id', $getting_id)
        ->value('profile_status');
// Decode the existing JSON data to an associative array
$existingArray = json_decode($existingData, true);
// Update the specific key in the array
$existingArray['socialurl'] = 'yes';
// Encode the array back to JSON
$newJsonData = json_encode($existingArray);
        if (!str_contains($existingData, 'socialurl')) {
            // Perform the update if "socialurl" is not present
            // Add your update logic here
            DB::table('addprofiles')
            ->where('user_id', $getting_id)
            ->update(['profile_status' => $newJsonData]);

            // Example: Update database record
            // $database->update('profiles', ['profile_status' => $adding_profile->profile_status], ['user_id' => $user_id]);
        } else {


        }
Enter fullscreen mode Exit fullscreen mode
   $existingData = DB::table('addprofiles')
              ->where('user_id', $user_id)
              ->value('profile_status');

      // Decode the existing JSON data to an associative array
      $existingArray = json_decode($existingData, true);

      // Update the specific key in the array
      $existingArray['price'] = 'yes';

      // Encode the array back to JSON
      $newJsonData = json_encode($existingArray);


              if (!str_contains($existingData, 'price')) {
                  // Perform the update if "socialurl" is not present
                  // Add your update logic here
                  DB::table('addprofiles')
                  ->where('user_id', $user_id)
                  ->update(['profile_status' => $newJsonData]);

                  // Example: Update database record
                  // $database->update('profiles', ['profile_status' => $adding_profile->profile_status], ['user_id' => $user_id]);
              } else {


              }
Enter fullscreen mode Exit fullscreen mode
 $existingData = DB::table('addprofiles')
        ->where('user_id', $getting_id)
        ->value('profile_status');

// Decode the existing JSON data to an associative array
$existingArray = json_decode($existingData, true);

// Update the specific key in the array
$existingArray['describe'] = 'yes';

// Encode the array back to JSON
$newJsonData = json_encode($existingArray);


        if (!str_contains($existingData, 'describe')) {
            // Perform the update if "socialurl" is not present
            // Add your update logic here
            DB::table('addprofiles')
            ->where('user_id', $getting_id)
            ->update(['profile_status' => $newJsonData]);

            // Example: Update database record
            // $database->update('profiles', ['profile_status' => $adding_profile->profile_status], ['user_id' => $user_id]);
        } else {


        }
Enter fullscreen mode Exit fullscreen mode
      $existingData = DB::table('addprofiles')
        ->where('user_id', $getting_id)
        ->value('profile_status');
// Decode the existing JSON data to an associative array
$existingArray = json_decode($existingData, true);
// Update the specific key in the array
$existingArray['describe'] = 'yes';
// Encode the array back to JSON
$newJsonData = json_encode($existingArray);
        if (!str_contains($existingData, 'describe')) {
            // Perform the update if "socialurl" is not present
            // Add your update logic here
            DB::table('addprofiles')
            ->where('user_id', $getting_id)
            ->update(['profile_status' => $newJsonData]);

            // Example: Update database record
            // $database->update('profiles', ['profile_status' => $adding_profile->profile_status], ['user_id' => $user_id]);
        } 
else {


        }

Enter fullscreen mode Exit fullscreen mode
  $existingData = DB::table('addprofiles')
  ->where('user_id', $user_id)
  ->value('profile_status');

// Decode the existing JSON data to an associative array
$existingArray = json_decode($existingData, true);

// Update the specific key in the array
$existingArray['pic'] = 'yes';

// Encode the array back to JSON
$newJsonData = json_encode($existingArray);


  if (!str_contains($existingData, 'pic')) {
      // Perform the update if "socialurl" is not present
      // Add your update logic here
      DB::table('addprofiles')
      ->where('user_id', $user_id)
      ->update(['profile_status' => $newJsonData]);

      // Example: Update database record
      // $database->update('profiles', ['profile_status' => $adding_profile->profile_status], ['user_id' => $user_id]);
  } else {


  }
Enter fullscreen mode Exit fullscreen mode

output
{"register":"yes","socialurl":"yes","price":"yes","describe":"yes","pic":"yes"}

In controller get data after storing in key-value pair

   public function influencer_dashboard($slug)
    {

        $a_user_api_bearer_token = $this->getOrganisationAccessToken();
        $total_order=sharedata::get(); 
        $pending_order=sharedata::where('status', '<>', 'completed')->get();
        $complete_order=sharedata::where('status','completed')->get();
        $order_sum=sharedata::sum('pay_amount');
        $completed_sum=sharedata::where('status','completed')->sum('pay_amount');
        $pending_sum=sharedata::where('status','pending')->sum('pay_amount');
        $id = Auth::user()->id;
        $profiles=Addprofile::where('user_id',$id)->first();
        log::info("profiles  hain naa");
        log::info($profiles);
        log::info($total_order);
        log::info($pending_order);
        log::info($complete_order);
        log::info($order_sum);
        return view('admin.influencer_dashboard', compact('a_user_api_bearer_token','completed_sum','pending_sum','profiles','total_order','pending_order','complete_order','order_sum'));

    }
Enter fullscreen mode Exit fullscreen mode
**Display data in blade file**
Enter fullscreen mode Exit fullscreen mode

Wap to count specific word from json format using array_filter

<div class="mdc-layout-grid__cell stretch-card mdc-layout-grid__cell--span-3-desktop mdc-layout-grid__cell--span-4-tablet">
              <div class="mdc-card info-card info-card--info">
                <div class="card-inner">
                  <h5 class="card-title">Profile Completeness</h5>
                  <h5 class="font-weight-light pb-2 mb-1 border-bottom"></h5>
                  <p class="tx-12 text-muted">
                    <span class="text-danger display-4">
                    @php 
    $profileData = json_decode($profiles->profile_status, true);

    // Check if json_decode was successful
    if ($profileData !== null && json_last_error() === JSON_ERROR_NONE) {
        $yesCount = count(array_filter($profileData, function($value) {
            return $value === 'yes';
        }));
        $completionPercentage = $yesCount * 20;
    } else {
        // Handle the case where JSON decoding failed
        $completionPercentage = 0;
    }
@endphp

{{{ $completionPercentage }}}%
                  </p>
                  <div class="card-icon-wrapper">

                    <i class="material-icons">dvr</i>
                  </div>
                </div>
              </div>
            </div>

          </div>
        </div>
      </main>
    </div>
  </div>
Enter fullscreen mode Exit fullscreen mode

output

Image description

Receive and Store Data from the Request:
In your Laravel application, create a controller and define a method to receive and store the dynamic key-value pairs coming with the request. For example:

public function storeKeyValues(Request $request)
{
    foreach ($request->all() as $key => $value) {
        DB::table('key_value_pairs')->updateOrInsert(
            ['key' => $key],
            ['value' => $value]
        );
    }

    return 'Key-value pairs stored successfully.';
}
Enter fullscreen mode Exit fullscreen mode

In this method, we use the updateOrInsert method to either insert a new key-value pair or update the value if the key already exists.

Access Data:

To retrieve data from the key_value_pairs table, you can use Laravel's Eloquent ORM or the query builder. For example:

use Illuminate\Support\Facades\DB;

$data = DB::table('key_value_pairs')->get();
Enter fullscreen mode Exit fullscreen mode

This will retrieve all the key-value pairs from the table.

Display and Use Data:

You can use the retrieved data in your Laravel application as needed, such as displaying it in views or using it in your application's logic.
Submit Data via a Form:

To submit dynamic key-value pairs from a form, create a form in your Laravel application with input fields for keys and values. Handle the form submission in your controller's method and store the data in the key_value_pairs table.
Testing:

Test your setup by submitting data via a form or making POST requests to your storeKeyValues route.

how to display key value pair data in html

In Laravel, you can store data as key-value pairs using various data structures, but one of the most common ways is by using associative arrays or collections. Here's a step-by-step example of how to store data as key-value pairs in Laravel:

Create a Laravel Project:
If you haven't already, you can create a new Laravel project using Laravel's command-line tools or Laravel Installer. Open your terminal and run:

laravel new key_value_example
cd key_value_example
Enter fullscreen mode Exit fullscreen mode

Create a Route:
Open the routes/web.php file and define a route to a controller method where you'll store and work with the key-value pairs. For example:

Route::get('/store-data', 'KeyValueController@storeData');
Enter fullscreen mode Exit fullscreen mode

Create a Controller:
Create a new controller using the following Artisan command:

php artisan make:controller KeyValueController
Enter fullscreen mode Exit fullscreen mode

Define a Method:
Open the KeyValueController.php file in the app/Http/Controllers directory and define a method to store key-value pairs. Here's a simple example:

public function storeData()
{
    $data = [
        'name' => 'John',
        'age' => 30,
        'city' => 'New York',
    ];

    return view('key_value_example', compact('data'));
}
Enter fullscreen mode Exit fullscreen mode

In this method, we define an associative array named $data with key-value pairs.

Create a View:
Create a Blade view file to display the stored key-value pairs. You can create a new file named key_value_example.blade.php in the resources/views directory. Here's a basic example of how you can display the data:

<html>
<head>
    <title>Key-Value Example</title>
</head>
<body>
    <h1>User Information</h1>
    <ul>
        @foreach ($data as $key => $value)
            <li><strong>{{ $key }}:</strong> {{ $value }}</li>
        @endforeach
    </ul>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

This Blade view iterates through the $data array and displays each key and its corresponding value.

Access the Route:
Start the development server by running:

php artisan serve
Enter fullscreen mode Exit fullscreen mode

Open your browser and navigate to http://localhost:8000/store-data. You should see the key-value pairs displayed on the web page.

In this example, we created a simple Laravel application that stores data as key-value pairs in an associative array and then displays the data on a web page using a Blade view. You can adapt this example to store and display more complex data structures, including data retrieved from databases or user input.

you have a profile_status field in your database that contains a JSON string with key-value pairs, and you want to display these values in a Blade file in Laravel, you can follow these steps:

Assuming you have a model (let's say Profile) that represents the data in your database, you can retrieve the profile_status field from the database and decode it as JSON in your controller. Then, pass it to your Blade view for rendering.

Here's an example:

Controller:

use App\Models\Profile;

class ProfileController extends Controller
{
    public function show($id)
    {
        $profile = Profile::find($id);

        // Assuming 'profile_status' is a JSON field in the database
        $profileStatus = json_decode($profile->profile_status, true);

        return view('profiles.show', compact('profile', 'profileStatus'));
    }
}
Enter fullscreen mode Exit fullscreen mode

Blade View (profiles/show.blade.php):

@extends('layouts.app')

@section('content')
    <h1>User Profile</h1>

    <ul>
        @foreach ($profileStatus as $key => $value)
            <li>{{ ucfirst($key) }}: {{ ucfirst($value) }}</li>
        @endforeach
    </ul>
@endsection

Enter fullscreen mode Exit fullscreen mode

In this example, we assume that the keys and values in the profile_status JSON correspond to some kind of user profile status. The json_decode($profile->profile_status, true) function decodes the JSON string into an associative array.

In the Blade view, we use a foreach loop to iterate through the key-value pairs and display them. The ucfirst() function is used to capitalize the first letter of each word, making the output more readable.

Adjust the code according to your specific needs and the structure of your database and application.

how to apply condition while iterating array of data

Wap to apply condition on retrive data collection of associative array contain key value pair

 $categories  = $this->category->get_categories();
            foreach($categories as $key=> $value)
            {
                if($value['category'] == $category)
                    $category_id = $value['id'];
            }
Enter fullscreen mode Exit fullscreen mode
$categories = $this->category->get_categories(); // Assuming this gets an array of categories
$category = 'Category C'; // The specific category you want to find the ID for
$category_id = null; // Initialize the category ID variable as null
foreach ($categories as $key => $value) {
    if ($value['name'] == $category) {
        $category_id = $value['id'];
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation
step1:get data and returns as array using to_array

public function get_categories()
{
    // $category = Tripcategory::get();
    $category = Tripcategory::offset(0)->limit(9)->get();
    return to_array($category);
}
Enter fullscreen mode Exit fullscreen mode

database table named tripcategories with the following data:
Image description

output
Image description

step2:iterates through the array of categories obtained from the get_categories() method

foreach ($categories as $key => $value) {
    if ($value['name'] == $category) {
        $category_id = $value['id'];
    }
}
Enter fullscreen mode Exit fullscreen mode
// Sample $categories array
$categories = array(
    array('id' => 1, 'category' => 'Electronics'),
    array('id' => 2, 'category' => 'Clothing'),
    array('id' => 3, 'category' => 'Books'),
);
Enter fullscreen mode Exit fullscreen mode

complete code

protected function event_filters(Request $request)
    {
        $request->validate([
            'category'          => 'max:256|String|nullable',
            'search'            => 'max:256|String|nullable',
            'start_date'        => 'date_format:Y-m-d|nullable',
            'end_date'          => 'date_format:Y-m-d|nullable',
            'price'             => 'max:256|String|nullable',
            'city'              => 'max:256|String|nullable',
            'state'             => 'max:256|String|nullable',
            'country'           => 'max:256|String|nullable',
        ]);
        $category_id            = null;
        $category               = urldecode($request->category);
        $search                 = $request->search;
        $price                  = $request->price;
        $city                   = urldecode($request->city);
        $state                  = urldecode($request->state);
        $country_id             = null;
        $state_id               = null;
        $city_id                = null;
        $country                = urldecode($request->country);
        // search category id
        if(!empty($category))
        {
            $categories  = $this->category->get_categories();
            foreach($categories as $key=> $value)
            {
                if($value['category'] == $category)
                    $category_id = $value['id'];
            }
        }
        // search country id
        if(!empty($country))
        {
            $countries = $this->country->get_mycountries();
            foreach($countries as $key=> $value)
            {
                if($value['country_name'] == $country)
                    $country_id = $value['country_id'];
            }
        }
        // if(!empty($state))
        // {
        //     $states = $this->state->get_states();
        //     foreach($states as $key=> $value)
        //     {
        //         if($value['state_name'] == $state)
        //             $state_id = $value['state_id'];
        //     }
        // }
        // if(!empty($city))
        // {
        //     $cities = $this->city->get_cities();
        //     log::info($cities);
        //     foreach($cities as $key=> $value)
        //     {
        //         if($value['city_name'] == $city)
        //             $city_id = $value['city_id'];
        //     }
        // }
        if(!empty($state))
        {
            $states = $this->state->get_mystates();
            foreach($states as $key=> $value)
            {
                if($value['state_name'] == $state)
                    $state_id = $value['state_id'];
            }
        }
        if(!empty($city))
        {
            $cities = $this->city->myget_cities();
            log::info($cities);
            foreach($cities as $key=> $value)
            {
                if($value['city_name'] == $city)
                    $city_id = $value['city_id'];
            }
        }
        $filters                    = [];
        $filters['category_id']     = $category_id;
        $filters['search']          = $search;
        $filters['price']           = $price;
        $filters['start_date']      = $request->start_date;
        $filters['end_date']        = $request->end_date;
        $filters['city_id']          = $city_id;
        $filters['state_id']        = $state_id;
        $filters['country_id']      = $country_id;
        // in case of today and tomorrow and weekand
        if($request->start_date == $request->end_date)
            $filters['end_date']     = null;
        return $filters;
    }
Enter fullscreen mode Exit fullscreen mode

Another Example

 public static function reportstatus($id)          
    {    
        $task = new sharedata(); 
        $approvetask  = $task->get_task($id);
        $influencer_email= null;
        $influencer_name= null;
        $Paytm = new Paytm(); 
        $Paytmdata  = $Paytm->get_paytm();
        log::info($Paytmdata);
        $admin_id=$approvetask->admin_id;
        $payment_id=$approvetask->payment_id;
        log::info("approvetask aata hain");
        log::info($id);
        log::info($admin_id);
        log::info($approvetask);
        foreach($Paytmdata as $key=> $value)
        {
            if($value['id'] == $payment_id)
                $influencer_email = $value['influencer_email'];
        }
        foreach($Paytmdata as $key=> $value)
        {
            if($value['id'] == $payment_id)
                $influencer_name = $value['influencer_name'];
        }
        log::info($influencer_email);
        return response()->json([
            'approvetask' => $approvetask,
            'influencer_email' => $influencer_email,
            'influencer_name' => $influencer_name,
        ]);

        } 
Enter fullscreen mode Exit fullscreen mode

Explanation

$Paytmdata  = $Paytm->get_paytm();
 log::info($Paytmdata)
Enter fullscreen mode Exit fullscreen mode

output

array (
  0 => 
  array (
    'id' => 222,
    'payment_id' => 'PAYID-ORDS46626876',
    'influencer_admin_id' => '[22,21]',
    'payer_id' => NULL,
    'payer_email' => NULL,
    'amount' => 1.1,
    'currency' => NULL,
    'payment_status' => 'approved',
    'admin_id' => '21',
    'user_name' => 'Roshan kumar jha',
    'Pay_date' => '2023-10-30',
    'cart_id' => '[163,164]',
    'slug' => NULL,
    'org_slug' => 'set',
    'order_id' => NULL,
    'admin_email' => 'roshan.cotocus@gmail.com',
    'influencer_email' => '["abc@gmail.com","roshan.cotocus@gmail.com"]',
    'influencer_name' => '["Amit","Roshan kumar jha"]',
    'created_at' => '2023-10-30T08:47:23.000000Z',
    'updated_at' => '2023-10-30T07:49:06.000000Z',
  ),
  1 => 
  array (
    'id' => 223,
    'payment_id' => 'PAYID-ORDS88544401',
    'influencer_admin_id' => '[22,21]',
    'payer_id' => NULL,
    'payer_email' => NULL,
    'amount' => 1.1,
    'currency' => NULL,
    'payment_status' => 'approved',
    'admin_id' => '21',
    'user_name' => 'Roshan kumar jha',
    'Pay_date' => '2023-10-31',
    'cart_id' => '[163,164]',
    'slug' => NULL,
    'org_slug' => 'set',
    'order_id' => NULL,
    'admin_email' => 'roshan.cotocus@gmail.com',
    'influencer_email' => '["abc@gmail.com","roshan.cotocus@gmail.com"]',
    'influencer_name' => '["Amit","Roshan kumar jha"]',
    'created_at' => '2023-10-31T06:22:59.000000Z',
    'updated_at' => '2023-10-31T05:24:30.000000Z',
  ),
  2 => 
  array (
    'id' => 224,
    'payment_id' => 'PAYID-ORDS19297181',
    'influencer_admin_id' => '[22,21]',
    'payer_id' => NULL,
    'payer_email' => NULL,
    'amount' => 1.1,
    'currency' => NULL,
    'payment_status' => 'approved',
    'admin_id' => '21',
    'user_name' => 'Roshan kumar jha',
    'Pay_date' => '2023-10-31',
    'cart_id' => '[163,164]',
    'slug' => NULL,
    'org_slug' => 'set',
    'order_id' => NULL,
    'admin_email' => 'roshan.cotocus@gmail.com',
    'influencer_email' => '["abc@gmail.com","roshan.cotocus@gmail.com"]',
    'influencer_name' => '["Amit","Roshan kumar jha"]',
    'created_at' => '2023-10-31T07:01:14.000000Z',
    'updated_at' => '2023-10-31T06:02:34.000000Z',
  ),
  3 => 
  array (
    'id' => 225,
    'payment_id' => 'PAYID-ORDS91540844',
    'influencer_admin_id' => '[22,21]',
    'payer_id' => NULL,
    'payer_email' => NULL,
    'amount' => 1.1,
    'currency' => NULL,
    'payment_status' => 'approved',
    'admin_id' => '21',
    'user_name' => 'Roshan kumar jha',
    'Pay_date' => '2023-10-31',
    'cart_id' => '[163,164]',
    'slug' => NULL,
    'org_slug' => 'set',
    'order_id' => NULL,
    'admin_email' => 'roshan.cotocus@gmail.com',
    'influencer_email' => '["abc@gmail.com","roshan.cotocus@gmail.com"]',
    'influencer_name' => '["Amit","Roshan kumar jha"]',
    'created_at' => '2023-10-31T07:04:07.000000Z',
    'updated_at' => '2023-10-31T06:05:25.000000Z',
  ),
)
Enter fullscreen mode Exit fullscreen mode

how to check specific value present or not in indexed arrays

my indexed array format

array (
  0 => 
  array (
    'id' => 222,
    'payment_id' => 'PAYID-ORDS46626876',
    'influencer_admin_id' => '[22,21]',
    'payer_id' => NULL,
    'payer_email' => NULL,
    'amount' => 1.1,
    'currency' => NULL,
    'payment_status' => 'approved',
    'admin_id' => '21',
    'user_name' => 'Roshan kumar jha',
    'Pay_date' => '2023-10-30',
    'cart_id' => '[163,164]',
    'slug' => NULL,
    'org_slug' => 'set',
    'order_id' => NULL,
    'admin_email' => 'roshan.cotocus@gmail.com',
    'influencer_email' => '["abc@gmail.com","roshan.cotocus@gmail.com"]',
    'influencer_name' => '["Amit","Roshan kumar jha"]',
    'created_at' => '2023-10-30T08:47:23.000000Z',
    'updated_at' => '2023-10-30T07:49:06.000000Z',
  ),
  1 => 
  array (
    'id' => 223,
    'payment_id' => 'PAYID-ORDS88544401',
    'influencer_admin_id' => '[22,21]',
    'payer_id' => NULL,
    'payer_email' => NULL,
    'amount' => 1.1,
    'currency' => NULL,
    'payment_status' => 'approved',
    'admin_id' => '21',
    'user_name' => 'Roshan kumar jha',
    'Pay_date' => '2023-10-31',
    'cart_id' => '[163,164]',
    'slug' => NULL,
    'org_slug' => 'set',
    'order_id' => NULL,
    'admin_email' => 'roshan.cotocus@gmail.com',
    'influencer_email' => '["abc@gmail.com","roshan.cotocus@gmail.com"]',
    'influencer_name' => '["Amit","Roshan kumar jha"]',
    'created_at' => '2023-10-31T06:22:59.000000Z',
    'updated_at' => '2023-10-31T05:24:30.000000Z',
  ),
  2 => 
  array (
    'id' => 224,
    'payment_id' => 'PAYID-ORDS19297181',
    'influencer_admin_id' => '[22,21]',
    'payer_id' => NULL,
    'payer_email' => NULL,
    'amount' => 1.1,
    'currency' => NULL,
    'payment_status' => 'approved',
    'admin_id' => '21',
    'user_name' => 'Roshan kumar jha',
    'Pay_date' => '2023-10-31',
    'cart_id' => '[163,164]',
    'slug' => NULL,
    'org_slug' => 'set',
    'order_id' => NULL,
    'admin_email' => 'roshan.cotocus@gmail.com',
    'influencer_email' => '["abc@gmail.com","roshan.cotocus@gmail.com"]',
    'influencer_name' => '["Amit","Roshan kumar jha"]',
    'created_at' => '2023-10-31T07:01:14.000000Z',
    'updated_at' => '2023-10-31T06:02:34.000000Z',
  ),
  3 => 
  array (
    'id' => 225,
    'payment_id' => 'PAYID-ORDS91540844',
    'influencer_admin_id' => '[22,21]',
    'payer_id' => NULL,
    'payer_email' => NULL,
    'amount' => 1.1,
    'currency' => NULL,
    'payment_status' => 'approved',
    'admin_id' => '21',
    'user_name' => 'Roshan kumar jha',
    'Pay_date' => '2023-10-31',
    'cart_id' => '[163,164]',
    'slug' => NULL,
    'org_slug' => 'set',
    'order_id' => NULL,
    'admin_email' => 'roshan.cotocus@gmail.com',
    'influencer_email' => '["abc@gmail.com","roshan.cotocus@gmail.com"]',
    'influencer_name' => '["Amit","Roshan kumar jha"]',
    'created_at' => '2023-10-31T07:04:07.000000Z',
    'updated_at' => '2023-10-31T06:05:25.000000Z',
  ),
)
Enter fullscreen mode Exit fullscreen mode
 foreach ($array as $item) {
        if ($item['payment_id'] === $paymentId) {
            return true; // Payment ID exists
        }
    }
Enter fullscreen mode Exit fullscreen mode

Summary

update(['addcarts' => "$admins_email:yes"])
apply foreach loop for key-value pair
retrive single value from colunm using value
get the data after spliting string using explode
get data through issets condition to avoid error if not data present initially empty database
apply if-else condition to match requirment on getting data

Top comments (0)