How to Filter 2D Array Rows by Another Array Rows While Excluding Common Rows?

Mary-Kate Olsen
Release: 2024-10-25 11:15:02
Original
323 people have browsed it

How to Filter 2D Array Rows by Another Array Rows While Excluding Common Rows?

Filter 2D Array Rows by Another ArrayRows

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>
Copy after login

After calling array_diff_assoc($array1, $array2), the output still includes the common row:

<code class="php">[
    [11 => 'common set']
]</code>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!