2 回答

TA貢獻1839條經驗 獲得超15個贊
您可以使用array_search函數來查找具有值的特定鍵
$json = '[{"key1":"value1","key2":"value2"}]';
$array = json_decode($json, true);
echo array_search("value2", $array[0]); //key2
echo $array[0]["key2"] //value2

TA貢獻1773條經驗 獲得超3個贊
您可以使用PHP array_search() 函數從數組中獲取特定值。以下是您需要遵循的示例代碼,
由于提供的 PHP 數組是 JSON 格式,您首先需要按如下方式對其進行解碼,
$jsonArray = '[{"key1":"value1","key2":"value2"}]';
$array = json_decode($jsonArray, true);
所以解碼后的數組會是這樣的,
Array
(
[0] => Array
(
[key1] => value1
[key2] => value2
)
)
然后你可以使用array_search()函數,
<?php
$jsonArray = '[{"key1":"value1","key2":"value2"}]';
$array = json_decode($jsonArray, true);
echo array_search("value1", $array[0]); // Search an array for the value "value1" and return its key. In this case the key will be "key1"
?>
注意: array_search()函數是最好的選擇。但是您也可以使用 afor-loop來迭代所有值并檢查是否與您需要的值匹配。但我建議使用array_search()函數。
希望這對你有幫助!
- 2 回答
- 0 關注
- 351 瀏覽
添加回答
舉報