回答編集履歴
1
見直し
answer
CHANGED
@@ -1,3 +1,14 @@
|
|
1
|
+
for-in文法をそのまま真似してかきたいのかもしれませんが、
|
2
|
+
郷に入っては郷に従え、
|
3
|
+
より便利な文法があれば使うべきだと思ったりもします。
|
4
|
+
|
5
|
+
一定のデータ構造を先頭から末尾まで一つずつ順に処理するものだと察して、
|
6
|
+
だったらforeachでいいじゃないか、という考え方です。
|
7
|
+
何番目のデータを処理しているか、を意識して処理したい場合には、
|
8
|
+
引数が0,1,2って連続している前提で、[count](https://www.php.net/manual/ja/function.count.php)関数を使うのも手ではないかと。
|
9
|
+
|
10
|
+
---
|
11
|
+
|
1
12
|
json文字列を[json_decode](https://www.php.net/manual/ja/function.json-decode.php)関数でデコードするときに、
|
2
13
|
オブジェクトと配列のどちらかを選択できます。
|
3
14
|
|
@@ -108,10 +119,66 @@
|
|
108
119
|
}
|
109
120
|
]
|
110
121
|
EOT;
|
111
|
-
$
|
122
|
+
$arr = json_decode($json, true);
|
112
123
|
$message = '';
|
113
|
-
foreach ($
|
124
|
+
foreach ($arr as $item){
|
114
125
|
$message .= $item['name'] . "\n```" . $item['gender'] . "```\n";
|
115
126
|
}
|
116
127
|
echo $message;
|
128
|
+
```
|
129
|
+
|
130
|
+
foreachじゃなくforにした事例:
|
131
|
+
```php
|
132
|
+
<?php
|
133
|
+
$json = <<<EOT
|
134
|
+
[
|
135
|
+
{
|
136
|
+
"age": 20,
|
137
|
+
"name": "Mccullough Blevins",
|
138
|
+
"gender": "male",
|
139
|
+
"company": "ARTWORLDS",
|
140
|
+
"email": "mcculloughblevins@artworlds.com",
|
141
|
+
"address": "257 Hillel Place, Yogaville, Tennessee, 5537"
|
142
|
+
},
|
143
|
+
{
|
144
|
+
"age": 25,
|
145
|
+
"name": "Casey Meadows",
|
146
|
+
"gender": "female",
|
147
|
+
"company": "TUBESYS",
|
148
|
+
"email": "caseymeadows@tubesys.com",
|
149
|
+
"address": "886 Cropsey Avenue, Kraemer, New Jersey, 7623"
|
150
|
+
},
|
151
|
+
{
|
152
|
+
"age": 27,
|
153
|
+
"name": "Lucinda Neal",
|
154
|
+
"gender": "female",
|
155
|
+
"company": "COMDOM",
|
156
|
+
"email": "lucindaneal@comdom.com",
|
157
|
+
"address": "802 Elton Street, Crown, Wyoming, 7838"
|
158
|
+
},
|
159
|
+
{
|
160
|
+
"age": 36,
|
161
|
+
"name": "Effie Martinez",
|
162
|
+
"gender": "female",
|
163
|
+
"company": "ZOINAGE",
|
164
|
+
"email": "effiemartinez@zoinage.com",
|
165
|
+
"address": "435 Tompkins Avenue, Rossmore, Washington, 5586"
|
166
|
+
},
|
167
|
+
{
|
168
|
+
"age": 28,
|
169
|
+
"name": "Rae Kirby",
|
170
|
+
"gender": "female",
|
171
|
+
"company": "ZIGGLES",
|
172
|
+
"email": "raekirby@ziggles.com",
|
173
|
+
"address": "719 Kimball Street, Muse, California, 4171"
|
174
|
+
}
|
175
|
+
]
|
176
|
+
EOT;
|
177
|
+
$arr = json_decode($json, true);
|
178
|
+
$message = '';
|
179
|
+
$cnt = count($arr);
|
180
|
+
for ($i = 0; $i < $cnt; $i++){
|
181
|
+
$message .= $arr[$i]['name'] . "\n```" . $arr[$i]['gender'] . "```\n";
|
182
|
+
}
|
183
|
+
echo $message;
|
117
184
|
```
|