3 回答

TA貢獻1829條經驗 獲得超6個贊
要通過數組項目的屬性找出數組的索引,請使用Array_column僅獲取該列/屬性的值,然后使用Array_search查找索引。
<?php
$inputZip = 35004;
$index = array_search($inputZip, array_column($zipCodes, 'zipcode')); // 0
print_r($zipCodes[$index]); // the entire object

TA貢獻1865條經驗 獲得超7個贊
要獲取由于必須使用的某些參數而過濾的數組的鍵,您可以array_keys使用array_filter。
例如
$array = [1,2,1,1,1,2,2,1,2,1];
$out = array_filter($array,function($v) {
return $v == 2;
});
print_r(array_keys($out));
輸出
Array
(
[0] => 1
[1] => 5
[2] => 6
[3] => 8
)
在PHP沙箱中嘗試以上示例
匹配您的實際數據結構。
$json = '[{"zipcode": 35004,"state abbreviation": "AL","latitude": 33.606379,"longitude": -86.50249,"city": "Moody","state": "Alabama"},{"zipcode": 35004,"state abbreviation": "AL","latitude": 33.606379,"longitude": -86.50249,"city": "Moody","state": "Alabama"},{"zipcode": 35005,"state abbreviation": "AL","latitude": 33.606579,"longitude": -86.50649,"city": "Moody","state": "Alabama"}]';
$array = json_decode($json);
$out = array_filter($array, function($v) use ($inputZip) {
return $v->zipcode == $inputZip; // for the below output $inputZip=35004
});
print_r(array_keys($out));
輸出
Array
(
[0] => 0
[1] => 1
)
在PHP沙箱中嘗試示例

TA貢獻1875條經驗 獲得超5個贊
根據您的代碼:
foreach ($zipCodes as $index => $location) { // index is a key
if ($inputZip == $location->zipcode) {
echo "Index is ".$index;
break;
}
}
var_dump($zipCodes[$index]);
我應該注意,看來您在做錯了什么,因為您不想像這樣存儲數據并一直循環循環。
- 3 回答
- 0 關注
- 177 瀏覽
添加回答
舉報