3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPで配列のキーと要素配列を入れ替える

Last updated at Posted at 2015-03-11

別のサイトで以下のような問いに答えたのですが、
普段こちらの方をよく利用するので、メモとして残したいと思います。

以下のようなチーム構成があって。


$engineer = [
    'hardware' => ['sakaguchi', 'ohkubo', 'toda'],
    'network' => ['tsuda', 'toda'],
    'software' => ['ishino', 'yamauchi', 'toda', 'hattori'],
    'design' => ['morita', 'ishino', 'yasuhara'],
];

逆に、構成員ごとに、どの仕事をしているかの配列にしたい場合。


$result = array_reduce(array_keys($engineer),
	function ($carry, $item) use($engineer) {
		array_walk($engineer[$item], function ($value) use(&$carry, $item) {
			$carry[$value][] = $item;
		});
		return $carry;
	},
[]);

結果


array(9) {
  ["sakaguchi"]=>
  array(1) {
    [0]=>
    string(8) "hardware"
  }
  ["ohkubo"]=>
  array(1) {
    [0]=>
    string(8) "hardware"
  }
  ["toda"]=>
  array(3) {
    [0]=>
    string(8) "hardware"
    [1]=>
    string(7) "network"
    [2]=>
    string(8) "software"
  }
  ["tsuda"]=>
  array(1) {
    [0]=>
    string(7) "network"
  }
  ["ishino"]=>
  array(2) {
    [0]=>
    string(8) "software"
    [1]=>
    string(6) "design"
  }
  ["yamauchi"]=>
  array(1) {
    [0]=>
    string(8) "software"
  }
  ["hattori"]=>
  array(1) {
    [0]=>
    string(8) "software"
  }
  ["morita"]=>
  array(1) {
    [0]=>
    string(6) "design"
  }
  ["yasuhara"]=>
  array(1) {
    [0]=>
    string(6) "design"
  }
}


3
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?