Debug School

rakesh kumar
rakesh kumar

Posted on

Mapping key value pair from char of array in laravel

dynamic mapping key value pair using array_combine
dynamic mapping key value pair using array_merge
store json key value pair after mapping key value pair

<?php

$originalArray = ["a", "b", "c", "d"];
$mappingArray = ["apple", "banana", "cherry", "date"];

$characterMapping = [];

// Ensure both arrays have the same length
if (count($originalArray) == count($mappingArray)) {
    // Create a key-value pair mapping
    $characterMapping = array_combine($originalArray, $mappingArray);
}

// Display the result
echo "Character Mapping:\n";
print_r($characterMapping);

?>
Enter fullscreen mode Exit fullscreen mode

output

Character Mapping:
Array
(
    [a] => apple
    [b] => banana
    [c] => cherry
    [d] => date
)
Enter fullscreen mode Exit fullscreen mode

dynamic mapping key value pair

<?php

use App\Models\Table1;
use App\Models\Table2;

// Fetch data from the first table
$data1 = Table1::pluck('column_name', 'id')->toArray();

// Fetch data from the second table
$data2 = Table2::pluck('column_name', 'id')->toArray();

// Combine the two arrays into a key-value pair
$combinedData = array_combine(array_keys($data1 + $data2), array_values($data1 + $data2));

// Display the result
echo "Key-Value Pair Mapping:\n";
print_r($combinedData);

?>
Enter fullscreen mode Exit fullscreen mode

Using array_merge

<?php

use App\Models\Table1;
use App\Models\Table2;

// Fetch data from the first table
$data1 = Table1::pluck('column_name', 'id')->toArray();

// Fetch data from the second table
$data2 = Table2::pluck('column_name', 'id')->toArray();

// Merge the two arrays to create a key-value pair mapping
$mergedData = array_merge($data1, $data2);

// Display the result
echo "Key-Value Pair Mapping:\n";
print_r($mergedData);

?>
Enter fullscreen mode Exit fullscreen mode

store json key value pair after mapping key value pair

<?php

use App\Models\MyModel;
use Illuminate\Support\Facades\DB;

// Fetch data from the first table
$data1 = Table1::pluck('column_name', 'id')->toArray();

// Fetch data from the second table
$data2 = Table2::pluck('column_name', 'id')->toArray();

// Combine the two arrays into a key-value pair
$combinedData = array_combine(array_keys($data1 + $data2), array_values($data1 + $data2));

// Convert the key-value pair to JSON
$jsonData = json_encode($combinedData);

// Create or update a record in the MyModel table
MyModel::updateOrCreate(
    ['id' => 1], // Specify the primary key or unique identifier for the record
    ['json_column' => $jsonData]
);

// Display the result
echo "Data saved successfully.\n";

?>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)