Filter rows of a 3d array where keys in a specific column satisfy a flat whitelist array
✔ Recommended Answer
- Prepare your whitelist so that the required values are the keys of a flat array.
- Call
array_filter()
to iterate each row of the sample array. - Try to eliminate as many elements from the whitelist array using the row's discipline keys. If there are none remaining, then the row satisfies the whitelist and should be retained.
Code: (Demo)
$get['disciplines'] = ['second' => 2, 'third' => 4, 'fourth' => 12];$filterBy = array_flip($get['disciplines']);var_export( array_filter( $array, fn($row) => !array_diff_key($filterBy, $row['disciplines']) ));
Source: stackoverflow.com
Answered By: mickmackusa
To filter rows of a 3D array where keys in a specific column satisfy a flat whitelist array, you can use the filter
method along with the includes
method. Here's an example code snippet that demonstrates this approach:
javascriptconst arr3D = [
[[1, 2, 3], 'foo'],
[[4, 5, 6], 'bar'],
[[7, 8, 9], 'baz'],
[[10, 11, 12], 'qux'],
];
const whitelist = [2, 5, 8, 11];
const filteredArr3D = arr3D.filter((row) => {
const key = row[0][1]; // assuming column 1 is the target column
return whitelist.includes(key);
});
console.log(filteredArr3D);
// Output: [ [ [ 1, 2, 3 ], 'foo' ], [ [ 4, 5, 6 ], 'bar' ], [ [ 7, 8, 9 ], 'baz' ], [ [ 10, 11, 12 ], 'qux' ] ]
In this example, we have a 3D array arr3D
with two columns. We want to filter the rows where the key in the second column is in the whitelist
array. We use the filter
method to iterate over the rows of the 3D array, and the includes
method to check if the key is in the whitelist
array. Finally, we return the rows that satisfy this condition.
Note that in this example, we assumed that column 1 is the target column. You can change the index value to target a different column.
Comments
Post a Comment