我有一些 PHP 变量集,我正在从中创建一个多维数组。现在,在该数组中,我想检查特定的键([font]
) 对于重复项。
如果发现重复项,则对应的相应值[lang]
and [weight]
应该合并。
这是我到目前为止所尝试的(这会取消设置/删除数组中的重复值):
// Font [0]
$font_1 = "Poppins";
$font_1_l = "Hindi, English";
$font_1_w = "700, 700i";
// Font [1]
$font_2 = "Lora";
$font_2_l = "Vietnamese, Japanese";
$font_2_w = "200, 300, 400, 400i";
// Font [2]
$font_3 = "Noto Sans";
$font_3_l = "Punjabi, Latin, Hindi";
$font_3_w = "200, 200i, 300, 300i, 400, 500";
// Font [3]
$font_4 = "Lora";
$font_4_l = "Greek, Roman, Vietnamese";
$font_4_w = "400, 400i, 500, 500b";
// Array of all the values
$font_f = array( array( 'font' => $font_1, 'lang' => $font_1_l, 'weight' => $font_1_w ), array( 'font' => $font_2, 'lang' => $font_2_l, 'weight' => $font_2_w ), array( 'font' => $font_3, 'lang' => $font_3_l, 'weight' => $font_3_w ), array( 'font' => $font_4, 'lang' => $font_4_l, 'weight' => $font_4_w ) );
// Printing the array for testing
echo "<pre>";
print_r( array_map("unserialize", array_unique(array_map("serialize", $font_f))) );
// Removing duplicates
$font_f_copy = $font_f; // Copy of $font_f for modification
$fonts = array(); // To get unique fonts
for( $i=0; $i<count($font_f); $i++ ) {
if ( in_array( $font_f[$i]['font'], $fonts ) ) {
unset($font_f_copy[$i]);
}
else {
$fonts[] = $font_f[$i]['font'];
}
}
// Printing $font_f_copy for testing
print_r($font_f_copy);
Output:
Array
(
[0] => Array
(
[font] => Poppins
[lang] => Hindi, English
[weight] => 700, 700i
)
[1] => Array
(
[font] => Lora
[lang] => Vietnamese, Japanese
[weight] => 200, 300, 400, 400i
)
[2] => Array
(
[font] => Noto Sans
[lang] => Punjabi, Latin, Hindi
[weight] => 200, 200i, 300, 300i, 400, 500
)
[3] => Array
(
[font] => Lora
[lang] => Greek, Roman, Vietnamese
[weight] => 400, 400i, 500, 500b
)
)
Array
(
[0] => Array
(
[font] => Poppins
[lang] => Hindi, English
[weight] => 700, 700i
)
[1] => Array
(
[font] => Lora
[lang] => Vietnamese, Japanese
[weight] => 200, 300, 400, 400i
)
[2] => Array
(
[font] => Noto Sans
[lang] => Punjabi, Latin, Hindi
[weight] => 200, 200i, 300, 300i, 400, 500
)
)
正如您在上面的代码中看到的,Font [1] 和 Font [3] 将具有相同的值[font]
即洛拉,所以[lang]
and [weight]
对于字体 [1] 应合并[lang]
and [weight]
分别为字体 [3]。
我想知道如何继续实现这一目标。