I have a big tLD array of 2200 items like:
$TestArray = array(".aero", ".airport.aero", ".cargo.aero", ".charter.aero", ".aetna");
i am want to convert them as below:
Array
(
[0] => Array
(
[tld] => .aero
[gTLD] => Array ( [0] => .airport.aero [1] => .cargo.aero [2] => .charter.aero )
)
[1] => Array
(
[tld] => .aetna
[gTLD] =>
)
)
You can see my code below:
$TldList = array();
$TestArray = array(".aero", ".airport.aero", ".cargo.aero", ".charter.aero", ".aetna");
foreach ($TestArray as $tld)
{
$LocalTld = array();
$TldBreakPoints = explode(".",$tld);
$gTLD = array();
$found = false;
if((count($TldBreakPoints)) > 2)
{
foreach ($TestArray as $tld2)
{
$TldBreakPoints2 = explode(".",$tld2);
if((count($TldBreakPoints2)) > 2)
{
if($tld == '.'.$TldBreakPoints2[2])
{
echo 'match gtld';
$found = true;
$gTLD[] = $tld2;
}else{
//Nothing
}
}else{
// Nothing
}
}
}else{
}
$LocalTld['tld'] = $tld;
if($found)
{
$LocalTld['gTLD'] = $gTLD;
}else{
$LocalTld['gTLD'] = '';
}
$TldList[] = $LocalTld;
}
echo '<pre>';
print_r($TldList);
Please help
Thanks
CodePudding user response:
$array = [ '.aero', '.airport.aero', '.cargo.aero', '.charter.aero', '.aetna' ];
$result = array_values(
array_reduce(
$array,
function ($carry, $item) {
if (substr_count($item, '.') === 1) {
$carry[$item] = [ 'tld' => $item, 'gTLD' => [] ];
} else {
$parts = preg_split('/^([.]. )([.]. )/', $item, -1, PREG_SPLIT_DELIM_CAPTURE PREG_SPLIT_NO_EMPTY);
$last = end($parts);
$carry[$last]['gTLD'][] = $item;
}
return $carry;
},
[]
)
);
print_r($result);
Assumptions:
- The TLDs contain only one dot.
- The gTLDs appear in the array after the TLD they will be assigned to.