Home > Enterprise >  PHP - combine array key values from separate to one array
PHP - combine array key values from separate to one array

Time:09-03

I have some doubts about returning array in PHP. I have the following code.. I am pretty new with PHP and I am not sure what is the best way to refactor following lines and get the specified result.

private static function mapNetworkSpecificValues(iterable $values): array
{
    Assert::allIsInstanceOf($values, Networks::class);
    return array_map(
        fn($value) => ['network' => strtolower((string) $value->getNetwork()), 'value' => $value->getValue()],
        iterator_to_array($values)
    );
}

Which returns:

"networks": [
            {
                "network": "facebook",
                "value": true
            },
            {
                "network": "twitter",
                "value": true
            },
            {
                "network": "linkedin",
                "value": true
            }
            ]

What I want is:

 "networks": [
             {
                "facebook" : true,
                "twitter"  : true,
                "linkedin" : true
            }
            ]

I tried with array_combine() like:

fn($value) => array_combine($value->getNetwork(), $value->getValue()

but I am not sure this is the right approach for this problem?

Thanks

CodePudding user response:

     // Initial array
     $networks = array(  array('network'=>'Facebook', 'value'=>true),
                        array('network'=>'Twitter', 'value'=>true),
                        array('network'=>'Instagram', 'value'=>true)
                    );

    // Step 1 , create seperate arrays with network as keys
    $mixed_array = array_map(
        function($value) { return [$value['network'] => $value['value']]; },
        $networks
    );

    // Step 2, merge these arrays
    $mixed_array2 = array_merge(...$mixed_array);

    print_r($mixed_array2);

Output:

Array ( [Facebook] => 1 [Twitter] => 1 [Instagram] => 1 )

I hope it helps.

  • Related