在循环时,第3循环未提供正确的输出。 第三循环应从第二阵列循环获得所有匹配的名称。 但是它仅从第二个数组中获取第一个数组项,而忽略所有其他数组项。
这里可以解释哪些?代码有问题吗?
<?php
$t = json_decode(file_get_contents('https://gist.githubusercontent.com/mshafrir/2646763/raw/8b0dbb93521f5d6889502305335104218454c2bf/states_titlecase.json'), true);
$reg_state_short = array();
$reg_state = array(
array('Connecticut',' Maine',' Massachusetts',' New Hampshire',' Rhode Island',' Vermont'),
array('New Jersey',' New York',' Puerto Rico',' US Virgin Islands'),
array('Delaware',' District of Columbia',' Maryland',' Pennsylvania',' Virginia',' West Virginia'),
array('Alabama',' Florida',' Georgia',' Kentucky',' Mississippi',' North Carolina',' South Carolina',' Tennessee'),
array('Illinois',' Indiana',' Michigan',' Minnesota',' Ohio',' Wisconsin'),
array('Arkansas',' Louisiana',' New Mexico',' Oklahoma',' Texas'),
array('Iowa',' Kansas',' Missouri',' Nebraska'),
array('Colorado',' Montana',' North Dakota',' South Dakota',' Utah',' Wyoming'),
array('Arizona',' California',' Hawaii',' Nevada',' American Samoa',' Guam',' Northern Mariana Islands'),
array('Alaska',' Idaho',' Oregon',' Washington')
);
foreach ($reg_state as $reg_state2) {
foreach ($reg_state2 as $state) {
foreach ($t as $t2) {
if ($t2['name'] === $state ) {
$reg_state_short[] = $t2['abbreviation'];
break;
}
}
}
}
print_r($reg_state_short);
答案 0 :(得分:0)
我使用以下代码比较了所有数组值。我希望这可以为您提供帮助:
Grid
答案 1 :(得分:0)
在$reg_state
例如:
' Maine'
应该是:
'Maine'
这是完整的代码:
$t = json_decode(file_get_contents('https://gist.githubusercontent.com/mshafrir/2646763/raw/8b0dbb93521f5d6889502305335104218454c2bf/states_titlecase.json'), true);
$reg_state_short = array();
$reg_state = array(
array('Connecticut','Maine','Massachusetts','New Hampshire','Rhode Island','Vermont'),
array('New Jersey','New York','Puerto Rico','US Virgin Islands'),
array('Delaware','District of Columbia','Maryland','Pennsylvania','Virginia','West Virginia'),
array('Alabama','Florida','Georgia','Kentucky','Mississippi','North Carolina','South Carolina','Tennessee'),
array('Illinois','Indiana','Michigan','Minnesota','Ohio','Wisconsin'),
array('Arkansas','Louisiana','New Mexico','Oklahoma','Texas'),
array('Iowa','Kansas','Missouri','Nebraska'),
array('Colorado','Montana','North Dakota','South Dakota','Utah','Wyoming'),
array('Arizona','California','Hawaii','Nevada','American Samoa','Guam','Northern Mariana Islands'),
array('Alaska','Idaho','Oregon','Washington')
);
foreach ($reg_state as $reg_state2) {
foreach ($reg_state2 as $state) {
foreach ($t as $t2) {
if ($t2['name'] === $state ) {
$reg_state_short[] = $t2['abbreviation'];
break;
}
}
}
}
print_r($reg_state_short);
答案 2 :(得分:0)
仅调整前导和尾随空格
您在$reg_state
中有前导空格,例如' Maine',' Massachusetts'
foreach ($reg_state as $reg_state2) {
foreach ($reg_state2 as $state) {
foreach ($t as $t2) {
if (trim($t2['name']) === trim($state) ) {
$reg_state_short[] = $t2['abbreviation'];
break;
}
}
}
}
print_r($reg_state_short);
我所做的是在trim
语句中使用if
修剪前导和尾随空格
trim($t2['name']) === trim($state)