合并相同键的数组值

时间:2022-04-24 12:18:55

I am trying to build a query string to use as a Google Font selection. The fontname and weight are being passed as an array.

我正在尝试构建一个用作Google字体选择的查询字符串。 fontname和weight将作为数组传递。

$fonts = array();

$fonts[] = array( 'family' => 'Lato', 'weight' => '400', );
$fonts[] = array( 'family' => 'Lato', 'weight' => '700i', );
$fonts[] = array( 'family' => 'Lato', 'weight' => '900', );
$fonts[] = array( 'family' => 'Open Sans', 'weight' => '400', );
$fonts[] = array( 'family' => 'Open Sans', 'weight' => '700', );
$fonts[] = array( 'family' => 'Open Sans', 'weight' => '800', );
$fonts[] = array( 'family' => 'Ubuntu', 'weight' => '400', );
$fonts[] = array( 'family' => 'Ubuntu', 'weight' => '500', );
$fonts[] = array( 'family' => 'Ubuntu', 'weight' => '7i00', );  

How can I merge the weights if the font family is same? So that it becomes like this?

如果字体系列相同,如何合并权重?这样就变成了这样?

Array
(
    [Lato] => 400,700i,900
    [Open+Sans] => 400,700,800
    [Ubuntu] => 400,500,700i
)  

I can't use array_merge_recursive since I am dealing with a single array and none of the other answers here helped me.

我不能使用array_merge_recursive,因为我正在处理单个数组,这里没有其他答案帮助我。

If you are going to tag this question as duplicate, please note that I have tried several answers before asking. None of them worked.

如果您要将此问题标记为重复,请注意我在询问之前尝试了几个答案。他们都没有工作。

4 个解决方案

#1


2  

With single foreach() you can achieve it like below:-

使用单个foreach(),您可以像下面这样实现: -

$new_array = array();

foreach ($fonts as $font){
    $new_value = !empty($new_array[$font['family']]) ? $new_array[$font['family']].','.$font['weight'] : $font['weight'];
    $new_array[$font['family']] =  $new_value;
}

echo "<pre/>";print_r($new_array);

Output:- https://eval.in/681838

输出: - https://eval.in/681838

#2


3  

Use two foreach statement to attain this

使用两个foreach语句来实现此目的

$newArr = array();
//make an array values for each family
foreach ($fonts as $val) {
  $newArr[$val['family']][] = $val['weight'];
}
//using implode join the array values
foreach ($newArr as &$val) {
  $val = implode(', ', $val);
}

var_dump($newArr); // would be the required array

#3


2  

Of course, there are vanilla PHP solutions as others have already mentioned, but I'd go for Laravel's Collection class.

当然,正如其他人已经提到的那样,有一些普通的PHP解决方案,但我会选择Laravel的Collection类。

This is not restricted to Laravel apps though, you just install a composer package and besides solving this particular problem, it brings a lot of goodness to your app and a handful of useful tools at your disposal. Let's see:

这不仅限于Laravel应用程序,您只需安装一个编写器包,除了解决这个特殊问题外,它还为您的应用程序和一些有用的工具带来了很多好处。让我们来看看:

collect($fonts)
    ->groupBy('family')
    ->map(function($item, $key) {
        return $item->pluck('weight');
    })
    ->toArray();

As simple as that. Here's the output:

就如此容易。这是输出:

[
     "Lato" => [
          "400",
          "700i",
          "900",
     ],
     "Open Sans" => [
          "400",
          "700",
          "800",
     ],
     "Ubuntu" => [
          "400",
          "500",
          "7i00",
     ],
]

You might want to go on and implode the values.

您可能希望继续并破坏这些值。

If not using Laravel, here's a standalone package for Laravel's Collection class. Installing, is just a matter of composer require tightenco/collect. you're just installing a single package, not the whole framework.

如果不使用Laravel,这里是Laravel的Collection类的独立包。安装,只是作曲家需要收紧/收集的问题。你只是安装一个包,而不是整个框架。

#4


1  

You can do it manually use one foreach statement.

您可以手动使用一个foreach语句。

function mergeFonts($fonts)
{
    $result = array();
    foreach ($fonts as $font) {
        if (array_key_exists($font['family'], $result)) {
            array_push($result[$font['family']], $font['weight']);
        }   else {
            $result[$font['family']] = array($font['weight']);
        }
    }
    return $result;
}

And:

和:

    $fonts = array();
    $fonts[] = array( 'family' => 'Lato', 'weight' => '400', );
    $fonts[] = array( 'family' => 'Lato', 'weight' => '700i', );
    $fonts[] = array( 'family' => 'Lato', 'weight' => '900', );
    $fonts[] = array( 'family' => 'Open Sans', 'weight' => '400', );
    $fonts[] = array( 'family' => 'Open Sans', 'weight' => '700', );
    $fonts[] = array( 'family' => 'Open Sans', 'weight' => '800', );
    $fonts[] = array( 'family' => 'Ubuntu', 'weight' => '400', );
    $fonts[] = array( 'family' => 'Ubuntu', 'weight' => '500', );
    $fonts[] = array( 'family' => 'Ubuntu', 'weight' => '7i00', );
    echo '<pre>';
    print_r(mergeFonts($fonts));
    /* The output:
     Array
    (
        [Lato] => Array
            (
                [0] => 400
                [1] => 700i
                [2] => 900
            )

        [Open Sans] => Array
            (
                [0] => 400
                [1] => 700
                [2] => 800
            )

        [Ubuntu] => Array
            (
                [0] => 400
                [1] => 500
                [2] => 7i00
            )

    )
    */

#1


2  

With single foreach() you can achieve it like below:-

使用单个foreach(),您可以像下面这样实现: -

$new_array = array();

foreach ($fonts as $font){
    $new_value = !empty($new_array[$font['family']]) ? $new_array[$font['family']].','.$font['weight'] : $font['weight'];
    $new_array[$font['family']] =  $new_value;
}

echo "<pre/>";print_r($new_array);

Output:- https://eval.in/681838

输出: - https://eval.in/681838

#2


3  

Use two foreach statement to attain this

使用两个foreach语句来实现此目的

$newArr = array();
//make an array values for each family
foreach ($fonts as $val) {
  $newArr[$val['family']][] = $val['weight'];
}
//using implode join the array values
foreach ($newArr as &$val) {
  $val = implode(', ', $val);
}

var_dump($newArr); // would be the required array

#3


2  

Of course, there are vanilla PHP solutions as others have already mentioned, but I'd go for Laravel's Collection class.

当然,正如其他人已经提到的那样,有一些普通的PHP解决方案,但我会选择Laravel的Collection类。

This is not restricted to Laravel apps though, you just install a composer package and besides solving this particular problem, it brings a lot of goodness to your app and a handful of useful tools at your disposal. Let's see:

这不仅限于Laravel应用程序,您只需安装一个编写器包,除了解决这个特殊问题外,它还为您的应用程序和一些有用的工具带来了很多好处。让我们来看看:

collect($fonts)
    ->groupBy('family')
    ->map(function($item, $key) {
        return $item->pluck('weight');
    })
    ->toArray();

As simple as that. Here's the output:

就如此容易。这是输出:

[
     "Lato" => [
          "400",
          "700i",
          "900",
     ],
     "Open Sans" => [
          "400",
          "700",
          "800",
     ],
     "Ubuntu" => [
          "400",
          "500",
          "7i00",
     ],
]

You might want to go on and implode the values.

您可能希望继续并破坏这些值。

If not using Laravel, here's a standalone package for Laravel's Collection class. Installing, is just a matter of composer require tightenco/collect. you're just installing a single package, not the whole framework.

如果不使用Laravel,这里是Laravel的Collection类的独立包。安装,只是作曲家需要收紧/收集的问题。你只是安装一个包,而不是整个框架。

#4


1  

You can do it manually use one foreach statement.

您可以手动使用一个foreach语句。

function mergeFonts($fonts)
{
    $result = array();
    foreach ($fonts as $font) {
        if (array_key_exists($font['family'], $result)) {
            array_push($result[$font['family']], $font['weight']);
        }   else {
            $result[$font['family']] = array($font['weight']);
        }
    }
    return $result;
}

And:

和:

    $fonts = array();
    $fonts[] = array( 'family' => 'Lato', 'weight' => '400', );
    $fonts[] = array( 'family' => 'Lato', 'weight' => '700i', );
    $fonts[] = array( 'family' => 'Lato', 'weight' => '900', );
    $fonts[] = array( 'family' => 'Open Sans', 'weight' => '400', );
    $fonts[] = array( 'family' => 'Open Sans', 'weight' => '700', );
    $fonts[] = array( 'family' => 'Open Sans', 'weight' => '800', );
    $fonts[] = array( 'family' => 'Ubuntu', 'weight' => '400', );
    $fonts[] = array( 'family' => 'Ubuntu', 'weight' => '500', );
    $fonts[] = array( 'family' => 'Ubuntu', 'weight' => '7i00', );
    echo '<pre>';
    print_r(mergeFonts($fonts));
    /* The output:
     Array
    (
        [Lato] => Array
            (
                [0] => 400
                [1] => 700i
                [2] => 900
            )

        [Open Sans] => Array
            (
                [0] => 400
                [1] => 700
                [2] => 800
            )

        [Ubuntu] => Array
            (
                [0] => 400
                [1] => 500
                [2] => 7i00
            )

    )
    */