3 回答

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

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
要獲取由于必須使用的某些參數(shù)而過濾的數(shù)組的鍵,您可以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沙箱中嘗試以上示例
匹配您的實(shí)際數(shù)據(jù)結(jié)構(gòu)。
$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貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超5個(gè)贊
根據(jù)您的代碼:
foreach ($zipCodes as $index => $location) { // index is a key
if ($inputZip == $location->zipcode) {
echo "Index is ".$index;
break;
}
}
var_dump($zipCodes[$index]);
我應(yīng)該注意,看來您在做錯(cuò)了什么,因?yàn)槟幌胂襁@樣存儲(chǔ)數(shù)據(jù)并一直循環(huán)循環(huán)。
- 3 回答
- 0 關(guān)注
- 173 瀏覽
添加回答
舉報(bào)