teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

追記

2021/09/20 10:37

投稿

tanat
tanat

スコア18778

answer CHANGED
@@ -1,3 +1,10 @@
1
+ 回答
2
+ ---
3
+
4
+ > ワードプレスのWP_Queryで、複数のタクソノミーで絞り込みする際
5
+
6
+ WordPressの事はあんまり知らないので、配列の構造についてのみの回答です。
7
+
1
8
  ```PHP
2
9
  foreach ($var as $key => $value) {
3
10
  $args["tax_query"] += array(
@@ -17,4 +24,116 @@
17
24
  'terms' => $value
18
25
  );
19
26
  }
27
+ ```
28
+
29
+
30
+ 捕捉
31
+ ---
32
+
33
+ 質問タイトルの
34
+ > phpにおける配列の操作について。連想配列内に、重複せずに同じキーを持つ配列を追加したい
35
+
36
+ からの推測ですが、おそらく
37
+
38
+ ```PHP
39
+ $args = array(
40
+ 'post_type' => 'post',
41
+ 'tax_query' => array(
42
+ 'relation' => 'AND',
43
+ array(
44
+ 'taxonomy' => 'tax1',
45
+ 'field' => 'slug',
46
+ 'terms' => 'action1',
47
+ ),
48
+ array(
49
+ 'taxonomy' => 'tax2',
50
+ 'field' => 'slug',
51
+ 'terms' => 'action2',
52
+ ),
53
+ ),
54
+ );
55
+ ```
56
+
57
+ の質問部分のキーが実際にどうなっているかを把握されていない様に思います。
58
+
59
+ ```PHP
60
+ $args = array(
61
+ 'post_type' => 'post',
62
+ 'tax_query' => array(
63
+ 'relation' => 'AND',
64
+ array(
65
+ 'taxonomy' => 'tax1',
66
+ 'field' => 'slug',
67
+ 'terms' => 'action1',
68
+ ),
69
+ array(
70
+ 'taxonomy' => 'tax2',
71
+ 'field' => 'slug',
72
+ 'terms' => 'action2',
73
+ ),
74
+ ),
75
+ );
76
+ var_dump($args);
77
+
78
+ ```
79
+
80
+ とすれば、以下の様に該当部分のキーが0,1であることが確認出来ます。
81
+
82
+ ```
83
+ array(2) {
84
+ ["post_type"]=>
85
+ string(4) "post"
86
+ ["tax_query"]=>
87
+ array(3) {
88
+ ["relation"]=>
89
+ string(3) "AND"
90
+ [0]=>
91
+ array(3) {
92
+ ["taxonomy"]=>
93
+ string(4) "tax1"
94
+ ["field"]=>
95
+ string(4) "slug"
96
+ ["terms"]=>
97
+ string(7) "action1"
98
+ }
99
+ [1]=>
100
+ array(3) {
101
+ ["taxonomy"]=>
102
+ string(4) "tax2"
103
+ ["field"]=>
104
+ string(4) "slug"
105
+ ["terms"]=>
106
+ string(7) "action2"
107
+ }
108
+ }
109
+ }
110
+
111
+ ```
112
+
113
+ 配列に対して、キーを指定しない括弧(`[]`)で値を追加すると
114
+ その時点で整数値のキーの最大値の次の値が自動的にキーになるので、回答の様なコードになります。
115
+
116
+ この辺りは以下の様なコードを試して挙動を見てみると分かりやすいかもしれません。
117
+ [PHPマニュアル 配列](https://www.php.net/manual/ja/book.array.php)のサンプルコードを試してみるのもお勧めです。
118
+
119
+ ```PHP
120
+
121
+ $arr[] = 1;
122
+ $arr[2] = 2;
123
+ $arr[] = 3;
124
+ var_dump($arr);
125
+
126
+ /**
127
+ 結果
128
+ array(3) {
129
+ [0]=>
130
+ int(1)
131
+ [2]=>
132
+ int(2)
133
+ [3]=>
134
+ int(3)
135
+ }
136
+
137
+ **/
138
+
20
139
  ```