PHP で多次元の配列や連想配列の階層を減らす・浅くする、連想配列から配列に変換する

2022/09/17

単一要素の連想配列

$someObj = [
    new DateTime()
];

var_dump($someObj);

/*
array(1) {
  [0] =>
  class DateTime#1 (3) {
    public $date =>
    string(26) "yyyy-mm-dd hh:ii:ss.xxxxxx"
    public $timezone_type =>
    int(3)
    public $timezone =>
    string(3) "UTC"
  }
}
*/

$someObj = array_shift($someObj);

var_dump($someObj);
/*
class DateTime#1 (3) {
  public $date =>
  string(26) "yyyy-mm-dd hh:ii:ss.xxxxxx"
  public $timezone_type =>
  int(3)
  public $timezone =>
  string(3) "UTC"
}
*/

複数要素の連想配列を配列に変換

$someObj = [
    'hoge' => new DateTime(),
    'piyo' => new DateTime(),
];

var_dump($someObj);

/*
array(2) {
  'hoge' =>
  class DateTime#1 (3) {
    public $date =>
    string(26) "yyyy-mm-dd hh:ii:ss.xxxxxx"
    public $timezone_type =>
    int(3)
    public $timezone =>
    string(3) "UTC"
  }
  'piyo' =>
  class DateTime#2 (3) {
    public $date =>
    string(26) "yyyy-mm-dd hh:ii:ss.xxxxxx"
    public $timezone_type =>
    int(3)
    public $timezone =>
    string(3) "UTC"
  }
}
*/

$array = [];
array_walk(
    $someObj,
    function($val) use (&$array) {
        $array[] = $val;
    }
);

var_dump($array);

/*
array(2) {
  [0] =>
  class DateTime#1 (3) {
    public $date =>
    string(26) "yyyy-mm-dd hh:ii:ss.xxxxxx"
    public $timezone_type =>
    int(3)
    public $timezone =>
    string(3) "UTC"
  }
  [1] =>
  class DateTime#2 (3) {
    public $date =>
    string(26) "yyyy-mm-dd hh:ii:ss.xxxxxx"
    public $timezone_type =>
    int(3)
    public $timezone =>
    string(3) "UTC"
  }
}
*/

配列の場合

今回は未使用。

$someObj = [
    'hoge' => new DateTime(),
    'piyo' => new DateTime(),
];

var_dump($someObj);

/*
array(2) {
  'hoge' =>
  class DateTime#1 (3) {
    public $date =>
    string(26) "yyyy-mm-dd hh:ii:ss.xxxxxx"
    public $timezone_type =>
    int(3)
    public $timezone =>
    string(3) "UTC"
  }
  'piyo' =>
  class DateTime#2 (3) {
    public $date =>
    string(26) "yyyy-mm-dd hh:ii:ss.xxxxxx"
    public $timezone_type =>
    int(3)
    public $timezone =>
    string(3) "UTC"
  }
}
*/

$array = call_user_func_array('array_merge', $someObj);

var_dump($array);
/*
PHP Warning:  array_merge(): Expected parameter 1 to be an array, object given ...
*/

よくよく考えたら今回のケースでは階層を減らす、ではなく配列にする、ですし……。


Written by Circle
A mound built by the accumulation of hyperlinks are like Kowloon.