前提
PHPでプログラムを作っています。
複雑な配列から新しく配列を作り直すプログラムの書き方がもう少し良い方法が無いか教えていただきたいです
発生している問題
PHP
1// このような変数があります。 2$schema = array( 3 'some_int' => array( 4 'type' => 'number', 5 'default' => 1, 6 ), 7 'some_object' => array( 8 'type' => 'object', 9 'items' => array( 10 'some_object_child_1' => array( 11 'type' => 'object', 12 'items' => array( 13 'some_object_grand_child_1_1' => array( 14 'type' => 'string', 15 'default' => 'some_object_grand_child_1_1', 16 ), 17 'some_object_grand_child_1_2' => array( 18 'type' => 'string', 19 'default' => 'some_object_grand_child_1_2', 20 ), 21 'some_object_grand_child_1_3' => array( 22 'type' => 'string', 23 'default' => 'some_object_grand_child_1_3', 24 ), 25 ), 26 ), 27 'some_object_child_2' => array( 28 'type' => 'object', 29 'items' => array( 30 'some_object_grand_child_2_1' => array( 31 'type' => 'string', 32 'default' => 'some_object_grand_child_2_1', 33 ), 34 'some_object_grand_child_2_2' => array( 35 'type' => 'string', 36 'default' => 'some_object_grand_child_2_2', 37 ), 38 'some_object_grand_child_2_3' => array( 39 'type' => 'string', 40 'default' => 'some_object_grand_child_2_3', 41 ), 42 ), 43 ), 44 ), 45 ), 46 'some_bool' => array( 47 'type' => 'boolean', 48 'default' => false, 49 ), 50); 51 52// ここからdefaultの値を取得して新しく配列を作ります 53foreach ( $schema as $key => $value ) { 54 if ( $value['type'] === 'object' ) { 55 $default[ $key ] = array(); 56 57 // ここから同じようなことを繰り返し書いている objectの中は無限に入れ子になる可能性があるのでもう少し良い書き方にしたい 58 foreach ( $value['items'] as $key_1 => $value_1 ) { 59 if ( $value_1['type'] === 'object' ) { 60 $default[ $key ][ $key_1 ] = array(); 61 62 foreach ( $value_1['items'] as $key_2 => $value_2 ) { 63 $default[ $key ][ $key_1 ][ $key_2 ] = $value_2['default']; 64 } 65 66 } else { 67 $default[ $key ][ $key_1 ] = $value_1['default']; 68 } 69 } 70 71 } else { 72 $default[ $key ] = $value['default']; 73 } 74} 75return $default;
今の状態のようにオブジェクトが増えた分だけforeachを増やせば出来ないことはないですが同じような記述が増えるのでもう少し良い記述が無いか探しています。
最終的にはこのようなかたちにしたいです
PHP
1array(3) { 2["some_int"]=> 3int(1) 4["some_object"]=> 5array(2) { 6["some_object_child_1"]=> 7array(3) { 8["some_object_grand_child_1_1"]=> 9string(27) "some_object_grand_child_1_1" 10["some_object_grand_child_1_2"]=> 11string(27) "some_object_grand_child_1_2" 12["some_object_grand_child_1_3"]=> 13string(27) "some_object_grand_child_1_3" 14} 15["some_object_child_2"]=> 16array(3) { 17["some_object_grand_child_2_1"]=> 18string(27) "some_object_grand_child_2_1" 19["some_object_grand_child_2_2"]=> 20string(27) "some_object_grand_child_2_2" 21["some_object_grand_child_2_3"]=> 22string(27) "some_object_grand_child_2_3" 23} 24} 25["some_bool"]=> 26bool(false) 27}
補足情報(FW/ツールのバージョンなど)
最終的にはWordPressのregister_settingのdefaultとpropertiesの値に入れるための処理です
https://developer.wordpress.org/reference/functions/register_setting/#comment-5289
回答1件
あなたの回答
tips
プレビュー