[英]Returning Json Data To PHP Variables
我知道這里有很多類似的問題,但是我一直遇到的問題是設置其他json文件數組的方法與我的不同。
我想做的事情應該只是一個簡單的過程,但是由於我不熟悉json數組,而我還有其他事情,因此解決方案使我完全無法理解。
我只想將數據顯示在本地json文件中,並為返回的每個項目創建PHP變量。
json文件很簡單,看起來像這樣...
[
{
"titleOne": "Foo",
"textOne": "Bar",
"titleTwo": "Foo",
"textTwo": "Bar"
}
]
它始終僅由這4個項目組成。 然后,我使用以下PHP讀取和解碼文件...
$data = file_get_contents ('./data.json');
$json = json_decode($data, true);
foreach ($json as $key => $value) {
foreach ($value as $key => $val) {
echo $key . '====>' . $val . '<br/>';
}
}
但這只是輸出數據。 我試圖使這四個項目中的每一個都成為變量。 例...
$titleOne
$textOne
$titleTwo
$textTwo
...以便變量可以以某種形式使用。
我發現了很多類似的問題,但是json數據的設置總是不同,導致結果出錯。
為什么不簡單地定義它是否總是只有4個:
$titleOne = $json[0]['titleOne'];
$textOne = $json[0]['textOne'];
$titleTwo = $json[0]['titleTwo'];
$textTwo = $json[0]['textTwo'];
您可以使用列表將元素提取到變量中。 請記住,它僅適用於數值數組。
$json = '[
{
"titleOne": "Foo",
"textOne": "Bar",
"titleTwo": "Foo",
"textTwo": "Bar"
}
]';
$json = json_decode($json, true);
foreach ($json as $object) {
list($titleOne, $textOne, $titleTwo, $textTwo) = array_values($object);
}
使用php時,您不能使用變量來命名另一個變量。
但是,您可以使用關聯數組來執行此操作。
json_decode($data, true);
的true
json_decode($data, true);
已經以關聯數組的形式返回數據。 為了訪問titleOne的值,您只需執行$json['titleOne']
。 這會給你Foo
。
使用php,您可以使用一個變量來命名另一個變量。 只需使用Variable變量 :
$a = 'var';
$$a = 'hello world';
echo $var;
// output : hello word
在您的情況下:
您不必將json數據包裝在數組中並進行2個循環:
{
"titleOne": "Foo",
"textOne": "Bar",
"titleTwo": "Foo",
"textTwo": "Bar"
}
您可以通過以下方式創建動態變量:
$data = file_get_contents ('./data.json');
$json = json_decode($data, true);
foreach ($json as $key => $val) {
$$key = $val;
}
echo $titleOne;
// output : Foo
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.