0

I have an associative multidimensional array with multiple state ids:

array:2 [
  0 => array:2 [
    "url" => "http://www.kerluke.net/qui-sint-debitis-quo-et-suscipit-dolores-dolor-quae"
    "us_states_ids" => array:2 [
      0 => "15"
      1 => "16"
    ]
  ]
  1 => array:2 [
    "url" => "http://www.migato.net/qui-sint-debitis-quo-et-suscipit-dolores-dolor-quae"
    "us_states_ids" => array:3 [
      0 => "15"
      1 => "24"
      2 => "28"
    ]
  ]
]

Now I want to find duplicate ids for us_states_ids as you can see index 1 has id of 15 same as index 2. How can I achieve this?

2 Answers 2

3

Try looping the array and play around with array_intersect on current "us_state_ids" with the previous one if it is not the first iteration.

$duplicates = [];
for ($i = 1; $i < count($arr); $i++) {
    $prevStateIds = $arr[$i - 1]["us_states_ids"];
    $stateIds = $arr[$i]["us_states_ids"];
    $duplicates = array_merge($dupicates, array_intersect($prevStateIds, $stateIds));
  }
}

then $duplicates will have the duplicates. The above code is untested, it's just for a reference.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use array_intersect() to get duplicates:

$duplicates = [];
foreach($arr as $a) {
    foreach($arr as $b) {
        if ($a !== $b) {
            $duplicates = [ ...$duplicates, ...array_intersect($a["us_states_ids"], $b["us_states_ids"]) ];
        }
    }
}
$duplicates = array_unique($duplicates);

1 Comment

You're welcome. The two solutions are more or less the same. Use which one you like better :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.