I've spend couple of hours on this problem. I have a multidimension array with fonts details and I want to merge it to send one request to google web fonts. (Each array describe font details of different html tag) Anyone can help me with that?
Input:
Array
(
[1] => Array
(
[family] => Abril Fatface
[weight] => regular
[charset] => latin,latin-ext
)
[2] => Array
(
[family] => Akronim
[weight] => regular
[charset] => latin
)
[3] => Array
(
[family] => Akronim
[weight] => regular, bold
[charset] => latin
)
[4] => Array
(
[family] => Akronim
[weight] => regular
[charset] => latin, latin-ext
)
[5] => Array
(
[family] => Acme
[weight] => regular
[charset] => latin
)
)
Output:
Array
[0] (
[family] => Abril Fatface
[weight] => regular
[charset] => latin,latin-ext
)
[1] (
[family] => Akronim
[weight] => regular, bold
[charset] => latin,latin-ext
)
[2] (
[family] => Acme
[weight] => regular
[charset] => latin
)
Function
function font_merge_unique($col, $arr, $exj)
{
$test = array();
foreach($arr AS $key => $row)
{
$test[$key] = strtolower(preg_replace('/[^A-Za-z0-9]/', '', $row[$col]));
foreach($exj AS $index)
{
$arr[$key][$index] = array_map('trim', (is_array($arr[$key][$index]) ? $arr[$key][$index] : explode(',', $arr[$key][$index])));
}
}
$unique = array_unique($test);
$dupes = array_diff_key($test, $unique);
$list = array();
foreach($unique AS $key => $n)
{
$list[$key] = $arr[$key];
}
foreach($dupes AS $di => $row)
{
$index = array_search($row, $unique);
foreach($exj AS $merge)
{
$list[$index][$merge] += $arr[$di][$merge];
}
}
foreach($list AS $index => $row)
{
foreach($exj AS $merge)
{
$list[$index][$merge] = implode(',', $list[$index][$merge]);
}
}
return array_values($list);
}
Usage
Param 3 (Array) List of keys in processed array to make (String|Array) values a unique comma separated String.
font_merge_unique('family', $array, array('weight','charset'))
Result
Array
(
[0] => Array
(
[family] => Abril Fatface
[weight] => regular
[charset] => latin,latin-ext
)
[1] => Array
(
[family] => Akronim
[weight] => regular,bold
[charset] => latin,latin-ext
)
[2] => Array
(
[family] => Acme
[weight] => regular
[charset] => latin
)
)