构建基于另一个关联数组的值关联数组 [英] Build associative array based on values of another associative array

查看:170
本文介绍了构建基于另一个关联数组的值关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在找一个优雅的方式把这个数组:

 阵列(
  [富] => 1
  [巴] => 1
  [ZIM] => 3
  [DIB] => 6
  [GIR] => 1
  [煤气] => 3

在此数组:

 阵列(
  [1] =>阵列(富,酒吧,GIR)
  [3] =>阵列(ZIM,煤气)
  [6] =>阵列(DIB)

注意:,还有就是键或值之间没有关系。它们是完全任意的,并用作仅是示例。由此产生的阵列应该是输入数组的值进行分组的关联数组。

谢谢!


解决方案

  $输入=阵列(
  '富'=> 1,
  '酒吧'=> 1,
  ZIM'=> 3,
  DIB'=> 6,
  '吉尔'=> 1,
  嘎斯=> 3
)$输出=阵列();
的foreach($输入为$ K => $ V){
  如果(!使用isset($输出[$ V])){
    $输出[$ V] =阵列();
  }  $输出[$ V] [] = $ K表;
}

I'm looking for an elegant way to turn this array:

Array (
  [foo] => 1
  [bar] => 1
  [zim] => 3
  [dib] => 6
  [gir] => 1
  [gaz] => 3
)

Into this array:

Array (
  [1] => Array ( foo, bar, gir ),
  [3] => Array ( zim, gaz ),
  [6] => Array ( dib )
)

Note:, there is no relationship between the keys or values. They are completely arbitrary and used as examples only. The resulting array should be an associative array grouped by the values of the input array.

Thanks!

解决方案

$input = array(
  'foo' => 1,
  'bar' => 1,
  'zim' => 3,
  'dib' => 6,
  'gir' => 1,
  'gaz' => 3
)

$output = array();
foreach ( $input as $k => $v ) {
  if ( !isset($output[$v]) ) {
    $output[$v] = array();
  }

  $output[$v][] = $k;
}

这篇关于构建基于另一个关联数组的值关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆