如何移除PHP二维数组中的重复ID?求解决方案
Solution to Remove Duplicate IDs from Nested PHP Array
Hey there! Since you're new to programming, let's break this down nice and simple—you've got a nested array from your Apriori function, and you want to extract all unique IDs without duplicates. Here's exactly how to do it:
Step-by-Step Explanation & Code
Your original array looks like this:
$mightAlsoLike = [ ["7"], ["32"], ["7", "32"] ];
First, we need to flatten this nested array into a single-dimensional list of IDs. Then we can easily remove duplicates.
Here's the code that does both:
// Flatten the nested array into one dimension $flattenedIds = array_merge(...$mightAlsoLike); // Remove duplicate values $uniqueIds = array_unique($flattenedIds); // Optional: Re-index the array to have sequential keys (0, 1, 2...) $uniqueIds = array_values($uniqueIds); // Check the result dd($uniqueIds); // Will output: ["7", "32"]
Let's break down what each part does:
array_merge(...$mightAlsoLike): The...(spread operator) takes each sub-array in your original variable and passes them as separate arguments toarray_merge. This combines all the IDs into one array:["7", "32", "7", "32"].array_unique($flattenedIds): This built-in PHP function scans the array and removes any duplicate values, leaving only["7", "32"].array_values($uniqueIds): Optional, but useful—array_uniquekeeps the original array keys, so this re-indexes the array to have clean, sequential numeric keys.
For Older PHP Versions (pre-5.6)
If you're using a PHP version that doesn't support the spread operator, use call_user_func_array instead to flatten the array:
$flattenedIds = call_user_func_array('array_merge', $mightAlsoLike);
That's it! This will give you a clean list of unique IDs from your nested array. 😊
内容的提问来源于stack exchange,提问作者Reynaldo
相关产品推荐
相关产品推荐

