When working with two-dimensional arrays, it becomes crucial to filter rows based on specific criteria. This article addresses a common challenge: filtering the rows of one array by the rows in another array while excluding common rows.
Issue:
An attempt to use array_diff_assoc() to achieve this filtering returns common rows instead of the intended unique rows.
<code class="php">$array1 = [ [12 => 'new q sets'], [11 => 'common set'] ]; $array2 = [ [11 => 'common set'] ];</code>
After calling array_diff_assoc($array1, $array2), the output still includes the common row:
<code class="php">[ [11 => 'common set'] ]</code>
Solution:
The root cause of the issue lies in the comparison mechanism used by array_diff_assoc(). It employs a strict comparison, meaning that the string representations of the values must match precisely. In the given example, the value associated with key 11 in both arrays is 'common set'. However, array_diff_assoc() treats them as distinct values because they are stored in different arrays.
To obtain the desired filtering behavior, we need to use a comparison that takes into account the actual values stored in the arrays. One way to achieve this is to convert all array elements to a common type before comparing them. Here's an example using json_encode():
<code class="php">$json_array1 = array_map('json_encode', $array1); $json_array2 = array_map('json_encode', $array2); $filtered_rows = array_diff_assoc($json_array1, $json_array2); $filtered_rows = array_map('json_decode', $filtered_rows);</code>
This approach converts each array element to a JSON string and ensures that the comparison is now based on the actual values. The filtering operation will correctly identify and return only the unique row:
<code class="php">[ [12 => 'new q sets'] ]</code>
The above is the detailed content of How to Filter 2D Array Rows by Another Array Rows While Excluding Common Rows?. For more information, please follow other related articles on the PHP Chinese website!