array_intersect() with 2d arrays in php

✔ Recommended Answer

You can create a function to filter students using multiple conditions, instead of trying to combine the 2 results.

The function :

/** * Here, $condition array of keys/values used to filter $data. * ex: ['name' => 'jone', 'grade' => 9] */function filterArray($data, $conditions){    if (empty($conditions)) {        return $data;    }        return array_filter($data, function($record) use ($conditions) {        // Check all given conditions        foreach ($conditions as $key => $value) {            // If doesn't match, return false (don't keep in filtered array)            if ($record[$key] != $value) return false;        }        // conditions passed, add to array        return true;    });}

Usage :

$students = [    ["name"=> 'k. l.james', "grade" => 8],    ["name"=> 'k. l.james', "grade" => 9],    ["name"=> 'e. musk', "grade" => 8],    ["name"=> 'jone', "grade" => 9],];print_r(filterArray($students, ['grade' => 8]));// out : [["name"=> 'k. l.james', "grade" => 8],["name"=> 'e. musk', "grade" => 8]]print_r(filterArray($students, ['name' => 'k. l.james']));// out : [["name"=> 'k. l.james', "grade" => 8], ["name"=> 'k. l.james', "grade" => 9]]print_r(filterStudents($students, ['grade' => 8, 'name' => 'k. l.james']));// out : [["name"=> 'k. l.james', "grade" => 8]]

Additional notes :

  • using global is discouraged, in the code below, $students are given by the function parameter.
  • No need to use the else statement after a "return early" pattern (if ($someCondition) { return; } else { }).


Answered By: Syscall

Method #2

The array_intersect() function in PHP only works with one-dimensional arrays, and cannot directly be used with multi-dimensional or 2D arrays. However, you can use a combination of other array functions to achieve the desired result.

One approach is to loop through each element of the first array, and use the array_intersect() function to find the common elements in the second array. You can then add these common elements to a new array.

Here's an example implementation:

function array_intersect_2d($array1, $array2) { $result = array(); foreach ($array1 as $subarray) { $common_elements = array_intersect($subarray, $array2); if (!empty($common_elements)) { $result[] = $common_elements; } } return $result; }

This function takes two 2D arrays as input and returns a new 2D array that contains only the elements that are common to both input arrays.

Note that this implementation assumes that the subarrays of the first input array have the same number of elements as the subarrays of the second input array. If this is not the case, you may need to modify the implementation to handle this.


Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755