You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除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 to array_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_unique keeps 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 22:37:37