简体   繁体   中英

How to get maximum key/values pair array from a associative array in PHP?

I have an associative array like below

[
    [
        'k1' => 'v1',
        'k2' => 'v2'
    ],
    [
        'k1' => 'v1',
        'k2' => 'v2',
        'k3' => 'v3'
    ],
    [
        'k1' => 'v1',
        'k2' => 'v2',
        'k3' => 'v3',
        'k4' => 'v4'
    ]
]

Is it possible to get 3rd array which has maximum key/value pair.

EDIT

Let me clear a bit.

  • array[0] contains 2 key/value pair.
  • array[1] contains 3 key/value pair.
  • array[2] contains 4 key/value pair.

So I need to get array which contains maximum key/value pair.

Thanks in advance

You can use bellow approach for getting your result :

$array = array(
                array('K1'=>'v1'),
                array('K1'=>'v1','K2'=>'v2'),
                array('K1'=>'v1','K2'=>'v2','K3'=>'v3')
                );
$maxs = array_keys($array, max($array));
print_r($maxs);

It will provide you output as :

Array ( [0] => 2 ) 

Then you can get your key value pairs according to your requirement after passing this maxs array value like this.

$myMaxValue = $array[$maxs[0]];
print_r($myMaxValue);

This provide you below result :

Array ( [K1] => v1 [K2] => v2 [K3] => v3 ) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM