<?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
)
)
)