Abhik Abhik - 13 days ago 6
PHP Question

Merge array values for same keys

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.

$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.

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

Answer

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

$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

Comments