3
17

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】call_user_func_array関数で多次元配列の階層を減らす

Last updated at Posted at 2019-01-24

配列が深すぎて、階層を浅くしたいな〜というときに使えます。
array_mergeを使うと長くなりますが、call_user_func_arrayを使用すれば一行で済みます。

私は職場で知りましたが、公式サイトのUser Contributed Notesに載っています!

php.net〜call_user_func_array

テスト用配列

配列$membersは、maleとfemaleにグループ分けされています。
この配列からグループ分けを取り払い、配列の階層を1つ減らします。

<?php
$members = array (
    'male' => array (
        0 => array(
            'id' => 1,
            'name' => 'Bob'
        ),
        1 => array(
            'id' => 2,
            'name' => 'John'
        ),
        2 => array(
            'id' => 3,
            'name' => 'Ben'
        )
    ),
    'female' => array (
        0 => array(
            'id' => 4,
            'name' => 'Kate'
        ),
        1 => array(
            'id' => 5,
            'name' => 'Jane'
        )
    )
);

var_dump($members);

/*
出力結果
array(2) {
  ["male"]=>
  array(3) {
    [0]=>
    array(2) {
      ["id"]=>
      int(1)
      ["name"]=>
      string(3) "Bob"
    }
    [1]=>
    array(2) {
      ["id"]=>
      int(2)
      ["name"]=>
      string(4) "John"
    }
    [2]=>
    array(2) {
      ["id"]=>
      int(3)
      ["name"]=>
      string(3) "Ben"
    }
  }
  ["female"]=>
  array(2) {
    [0]=>
    array(2) {
      ["id"]=>
      int(4)
      ["name"]=>
      string(4) "Kate"
    }
    [1]=>
    array(2) {
      ["id"]=>
      int(5)
      ["name"]=>
      string(4) "Jane"
    }
  }
}
*/

配列の階層を減らす

call_user_func_array("array_merge", 配列)だけで完結します。

$merge_members = call_user_func_array("array_merge", $members); 
var_dump($merge_members);

/*
出力結果
array(5) {
  [0]=>
  array(2) {
    ["id"]=>
    int(1)
    ["name"]=>
    string(3) "Bob"
  }
  [1]=>
  array(2) {
    ["id"]=>
    int(2)
    ["name"]=>
    string(4) "John"
  }
  [2]=>
  array(2) {
    ["id"]=>
    int(3)
    ["name"]=>
    string(3) "Ben"
  }
  [3]=>
  array(2) {
    ["id"]=>
    int(4)
    ["name"]=>
    string(4) "Kate"
  }
  [4]=>
  array(2) {
    ["id"]=>
    int(5)
    ["name"]=>
    string(4) "Jane"
  }
}
*/
3
17
0

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
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?