Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Explain the use of array map and array merge in laravel

How to apply array_merge on get() function
How to apply array_merge on pluck() function
How to apply array_merge on json_encoded data
Use of array_filter

In Laravel, you can use the array_map and array_merge functions to manipulate arrays. These functions are not Laravel-specific but are part of PHP's standard library and are often used in Laravel applications.

array_map Function:

  1. The array_map function applies a callback function to each element of an array and returns a new array with the modified values.
  2. It is particularly useful for transforming data in arrays . Here's an example of using array_map in Laravel:
$numbers = [1, 2, 3, 4, 5];

$squared = array_map(function ($number) {
    return $number * $number;
}, $numbers);

// $squared will contain [1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode

array_merge Function:

  1. The array_merge function is used to merge multiple arrays into a single array.
  2. It combines the keys and values of arrays, overwriting values from previous arrays with the same keys . Here's an example of using array_merge in Laravel:
$array1 = ['a' => 'apple', 'b' => 'banana'];
$array2 = ['b' => 'blueberry', 'c' => 'cherry'];

$merged = array_merge($array1, $array2);

// $merged will contain ['a' => 'apple', 'b' => 'blueberry', 'c' => 'cherry']
Enter fullscreen mode Exit fullscreen mode

more example

$users = [
    ['id' => 1, 'name' => 'Alice'],
    ['id' => 2, 'name' => 'Bob'],
    ['id' => 3, 'name' => 'Charlie'],
];

$additionalData = [
    ['id' => 4, 'name' => 'David'],
    ['id' => 5, 'name' => 'Eve'],
];

// Use array_merge to combine two arrays
$combinedUsers = array_merge($users, $additionalData);

// Use array_map to transform data
$squareIds = array_map(function ($user) {
    $user['id'] = $user['id'] * $user['id'];
    return $user;
}, $users);
Enter fullscreen mode Exit fullscreen mode

=======================================
Another Example

To add some other request fields to the $addcart object using array_map and array_merge, you can create an array with the additional fields you want to include and then use array_merge to merge it with the data retrieved from the addcart object. Here's how you can do it:

Assuming you have a request with additional fields, you can create an associative array with those fields. For example:

$requestData = [
    'field1' => $request->input('field1'),
    'field2' => $request->input('field2'),
    // Add as many fields as needed
];
Enter fullscreen mode Exit fullscreen mode

Next, you can retrieve the $addcart object and convert it to an array. Assuming that $addcart is an Eloquent model, you can convert it to an array using the toArray method:

$addcart = addcart::where('admin_id', $admin_id)->first();

if ($addcart) {
    $addcartData = $addcart->toArray();
} else {
    $addcartData = [];
}
Enter fullscreen mode Exit fullscreen mode

Now, you can use array_merge to merge the $addcartData and $requestData arrays, including the additional fields from the request:

$mergedData = array_merge($addcartData, $requestData);
Enter fullscreen mode Exit fullscreen mode

The $mergedData array will contain all the fields from the $addcart object along with the additional fields from the request.

Here's the full code:

$requestData = [
    'field1' => $request->input('field1'),
    'field2' => $request->input('field2'),
    // Add as many fields as needed
];

$addcart = addcart::where('admin_id', $admin_id)->first();

if ($addcart) {
    $addcartData = $addcart->toArray();
} else {
    $addcartData = [];
}
Enter fullscreen mode Exit fullscreen mode
$mergedData = array_merge($addcartData, $requestData);
Enter fullscreen mode Exit fullscreen mode

Now, the $mergedData array contains all the fields you need, including the ones from the $addcart object and the additional fields from the request.

Another Example

If you want to add some other request fields to each element in the collection retrieved with get() using array_map and array_merge, you can do it like this:

$admin_id = 123; // Replace with the actual admin_id

// Retrieve the addcart collection
$addcart = addcart::where('admin_id', $admin_id)->get();

if ($addcart->isNotEmpty()) {
    // Define the additional fields from the request
    $additionalFields = [
        'field1' => $request->input('field1'),
        'field2' => $request->input('field2'),
        // Add as many fields as needed
    ];

    // Use array_map to add the additional fields to each element in the collection
    $addcart = $addcart->map(function ($item) use ($additionalFields) {
        return array_merge($item->toArray(), $additionalFields);
    });
}
Enter fullscreen mode Exit fullscreen mode

output

Image description

Here's a step-by-step explanation:

1.First, you retrieve the addcart collection by applying a query filter to get the records for a specific admin_id.

2.Check if the collection is not empty (i.e., it contains records). If it's empty, you can skip further processing.

3.Define the additional fields you want to add to each element in the collection. These fields come from the request, and you can adjust the field names and values accordingly.

4.Use the map function on the collection to iterate through each element (record) and apply a callback function.

5.In the callback function, you use array_merge to merge the original data from the database (retrieved with $item->toArray()) and the additional fields defined earlier.

Now, the $addcart collection has been updated with the additional fields from the request for each element. You can use the updated collection in your Laravel application as needed.

Image description
=====================Another Practical Example================

  public function myorders($orderID)    
    {  
        log::info("data here myorders");  
        log::info($orderID); 
        $currentURL = url()->current(); 
        log::info($currentURL);
        $id = Auth::user()->id; 
        $user = Paytm::where('order_id', $orderID)->first();       
        log::info('now myorder' . $user);  
        log::info($user);

        if ($user) {
            $user = $user->toArray();
        } else {
            $user = [];
        }

        $sharedata = sharedata::where('orders_id', $orderID)->first(); 
        if ($sharedata) {
            $sharedata = ['orders_id' => $sharedata->orders_id];
        } else {
            $sharedata = [];
        }

        log::info($sharedata);

        $users = array_merge($user, $sharedata);
        log::info($users);

        return view('pages.orderconfirm', compact('users', 'currentURL'));
       // return view('pages.myorder', compact('data'));
    }
Enter fullscreen mode Exit fullscreen mode

How to apply array_merge on get() function

wap to merge two table data in db

use App\Models\Model1;
use App\Models\Model2;

public function mergeData()
{
    // Retrieve data from the first table (Model1)
    $data1 = Model1::select('column1', 'column2')->get();

    // Retrieve data from the second table (Model2)
    $data2 = Model2::select('column3', 'column4')->get();

    // Convert collections to arrays
    $array1 = $data1->toArray();
    $array2 = $data2->toArray();

    // Merge the arrays
    $mergedData = array_merge($array1, $array2);

    // Output the merged data
    dd($mergedData);
}
Enter fullscreen mode Exit fullscreen mode

How to apply array_merge on pluck() function

use App\Models\Model1;
use App\Models\Model2;

public function mergeData()
{
    // Retrieve specific columns from the first table (Model1)
    $data1Column1 = Model1::pluck('column1');
    $data1Column2 = Model1::pluck('column2');

    // Retrieve specific columns from the second table (Model2)
    $data2Column3 = Model2::pluck('column3');
    $data2Column4 = Model2::pluck('column4');

    // Merge the plucked data using array_merge
    $mergedData = array_merge($data1Column1, $data1Column2, $data2Column3, $data2Column4);

    // Output the merged data
    dd($mergedData);
}
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

How to apply array_merge on json_encode

use App\Models\Model1;
use App\Models\Model2;

public function mergeData()
{
    // Retrieve data from the first table (Model1)
    $data1 = Model1::select('column1', 'column2')->get();

    // Retrieve data from the second table (Model2)
    $data2 = Model2::select('column3', 'column4')->get();

    // Convert collections to arrays
    $array1 = $data1->toArray();
    $array2 = $data2->toArray();

    // Merge the arrays
    $mergedData = array_merge($array1, $array2);

    // Encode the merged data to JSON
    $jsonEncodedData = json_encode($mergedData);

    // Output the JSON-encoded data
    dd($jsonEncodedData);
}
Enter fullscreen mode Exit fullscreen mode

output

$array1 = [
    ['column1' => 'value1', 'column2' => 10],
    ['column1' => 'value2', 'column2' => 20],
];

$array2 = [
    ['column3' => 'value3', 'column4' => 30],
    ['column3' => 'value4', 'column4' => 40],
];

// Merge the arrays
$mergedData = array_merge($array1, $array2);

// Encode the merged data to JSON
$jsonEncodedData = json_encode($mergedData);

// Output the JSON-encoded data
dd($jsonEncodedData);
Enter fullscreen mode Exit fullscreen mode
[
    {"column1":"value1","column2":10},
    {"column1":"value2","column2":20},
    {"column3":"value3","column4":30},
    {"column3":"value4","column4":40}
]
Enter fullscreen mode Exit fullscreen mode
  public function myorders($orderID)    
    {  
        log::info("data here myorders");  
        log::info($orderID); 
        $currentURL = url()->current(); 
        log::info($currentURL);
        $id = Auth::user()->id; 
        $user = Paytm::where('order_id', $orderID)->first();       
        log::info('now myorder' . $user);  
        log::info($user);

        if ($user) {
            $user = $user->toArray();
        } else {
            $user = [];
        }

        $sharedata = sharedata::where('orders_id', $orderID)->first(); 
        if ($sharedata) {
            $sharedata = ['orders_id' => $sharedata->orders_id];
        } else {
            $sharedata = [];
        }

        log::info($sharedata);

        $users = array_merge($user, $sharedata);
        log::info($users);

        return view('pages.orderconfirm', compact('users', 'currentURL'));
       // return view('pages.myorder', compact('data'));
    }
Enter fullscreen mode Exit fullscreen mode

Use of array_filter

use App\Models\ParentModel;
use App\Models\ChildModel;

public function filterParentData()
{
    // Retrieve data from the ParentModel using the get() function
    $parentData = ParentModel::all();

    // Convert the collection to an array
    $parentArray = $parentData->toArray();

    // Apply array_filter to filter parent items based on child data existence
    $filteredData = array_filter($parentArray, function ($parentItem) {
        // Check if child data exists based on the foreign key relationship
        $hasChildData = ChildModel::where('parent_id', $parentItem['id'])->exists();

        // Include the parent item only if child data exists
        return $hasChildData;
    });

    // Output the filtered data
    dd($filteredData);
}
Enter fullscreen mode Exit fullscreen mode

ParentModel (table: parents):

Image description

ChildModel (table: children):

Image description

array:2 [
  0 => [
    "id" => 1,
    "name" => "Parent A",
  ],
  1 => [
    "id" => 3,
    "name" => "Parent C",
  ],
]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)