douzhong4222
2019-05-10 06:25
浏览 223
已采纳

php从多维数组中获取最多和最少的值

I want to get most and least occuring values from php sequential/indexes, assoc and multidimensional arrays

Consider the following dataSet

        $dataSet = [
            'users' => 
            [
                'id' => 1,
                'name' => "Alex",
                'username' => 'alex',
            ],
            [
                'id' => 2,
                'name' => "Alex",
                'username' => 'alex'
            ],
            [
                'id' => 2,
                'name' => "Peter Khot",
                'username' => 'peter',
            ]
        ];

Here above are samples dataSet

Here is what that i tried

    function most_occurring(array $array, $key)
    {
        $dataSet = [];
        $i = 0;
        $keys = [];
        foreach ($array as $k) {
            if (in_array($k[$key], $keys)) {
                $keys[$i] = $k[$key];
                $dataSet[$i] = $k;
            } 

            $i++;
        }

        return $dataSet;
    }

I tried above code for most occurring values but not working at all, help me in most and least occuring values from arrays. Thanks

图片转代码服务由CSDN问答提供 功能建议

我想从php顺序/索引,关联和多维数组中获取最多和最少的值</ p> \ n

考虑以下dataSet </ p>

  $ dataSet = [
'users'=&gt;  
 [
'id'=&gt;  1,
'name'=&gt;  “Alex”,
'用户名'=&gt;  'alex',
],
 [
'id'=&gt;  2,
'name'=&gt;  “Alex”,
'用户名'=&gt;  'alex'
],
 [
'id'=&gt;  2,
'name'=&gt;  “Peter Khot”,
'用户名'=&gt;  'peter',
] 
]; 
 </ code> </ pre> 
 
 

上面是示例dataSet </ p>

这是我试过的 </ p>

  function most_occurring(array $ array,$ key)
 {
 $ dataSet = []; 
 $ i =  0; 
 $ keys = []; 
 foreach($ array as $ k){
 if(in_array($ k [$ key],$ keys)){
 $ keys [$ i] = $ k  [$ key]; 
 $ dataSet [$ i] = $ k; 
} 
 
 $ i ++; 
} 
 
返回$ dataSet; 
} 
 </ code> </ pre  > 
 
 

我在上面的代码中尝试了大多数出现的值但根本没有工作,帮助我从数组中获取大多数和最少的值。 谢谢</ p> </ div>

2条回答 默认 最新

相关推荐 更多相似问题