Chris Beckett Chris Beckett - 1 month ago 6
PHP Question

How to remove any records from array which don't have duplicates key?

<?php

$temp = [];
$array = [];

$array[] = array("parent_id" => 1, "parent" => "Mr & Mrs Lacey", "child_firstname" => "callum", "child_lastname" => "lacey");
$array[] = array("parent_id" => 2, "parent" => "Mr and Mrs Lacey", "child_firstname" => "daniel", "child_lastname" => "lacey");
$array[] = array("parent_id" => 3, "parent" => "Mr and Mrs Lacey", "child_firstname" => "sam", "child_lastname" => "lacey");
$array[] = array("parent_id" => 4, "parent" => "Mr and Mrs Dunn", "child_firstname" => "daniel", "child_lastname" => "dunn");
$array[] = array("parent_id" => 5, "parent" => "Mr and Mrs Parker", "child_firstname" => "sam", "child_lastname" => "parker");


function stripString($input){
$input = preg_replace("/[^a-zA-Z]+/", "", $input);
return $input;
}

foreach($array as $item){
$input = str_replace(" and ","", $item["parent"]);
$parent = stripString($input);
$child_firstname = stripString($item["child_firstname"]);
$child_lastname = stripString($item["child_lastname"]);

if(!array_key_exists($parent, $temp)) { //Add only first index details to array
$temp[$parent]['parent_id'] = $item["parent_id"];
$temp[$parent]['parent'] = $parent;
} else {
$temp[$parent]['duplicates'][] = $item["parent_id"];
}

// Remove unwanted indices
$temp[$parent][] = array("child_firstname" => $child_firstname,
"child_lastname" => $child_lastname);

}

$temp = array_values($temp); // Reset index

print_r($temp);


Printed out result:

Array
(
[0] => Array
(
[parent_id] => 1
[parent] => MrMrsLacey
[0] => Array
(
[child_firstname] => callum
[child_lastname] => lacey
)

[duplicates] => Array
(
[0] => 2
[1] => 3
)

[1] => Array
(
[child_firstname] => daniel
[child_lastname] => lacey
)

[2] => Array
(
[child_firstname] => sam
[child_lastname] => lacey
)

)

[1] => Array
(
[parent_id] => 4
[parent] => MrMrsDunn
[0] => Array
(
[child_firstname] => daniel
[child_lastname] => dunn
)

)

[2] => Array
(
[parent_id] => 5
[parent] => MrMrsParker
[0] => Array
(
[child_firstname] => sam
[child_lastname] => parker
)

)

)


Expected result:

Array
(
[0] => Array
(
[parent_id] => 1
[parent] => MrMrsLacey
[0] => Array
(
[child_firstname] => callum
[child_lastname] => lacey
)

[duplicates] => Array
(
[0] => 2
[1] => 3
)

[1] => Array
(
[child_firstname] => daniel
[child_lastname] => lacey
)

[2] => Array
(
[child_firstname] => sam
[child_lastname] => lacey
)
)
)

Answer

Use array_filter(), checking each element of the original array for duplicates key presence:

$with_duplicates = array_filter($temp, function($el) {
  return array_key_exists('duplicates', $el);
});

I used isset in the original version of this snippet, because it's used to be a bit faster than array_key_exists check. Still, the last one shows your intent more clearly (and won't fail on elements with duplicate property set to NULL for some reason).