![](/img/trans.png)
[英]How can i access json array in php and save it in .json file
[英]How can I access Json information in php using array indexing
我想獲取所有價格並添加它們。 我打算用它來循環通過 JSON 但這將是另一個問題。 我是以錯誤的方式接近這個嗎? 有沒有更好的方法來獲得所有價格的總和?
我發現這個答案提出了同樣的問題,但它不起作用(重復: PHP:如何使用數組索引訪問數組元素值)。 這是我的 JSON 字符串。
{
"data": {
"230723": {
"2019-11-15": {
"price": 52,
"min_length_of_stay": 2,
"available": 1
},
"2019-11-16": {
"price": 90,
"min_length_of_stay": 2,
"available": 0
},
"2019-11-17": {
"price": 44,
"min_length_of_stay": 2,
"available": 0
},
"2019-11-18": {
"price": 44,
"min_length_of_stay": 2,
"available": 0
}
}
}
}
這是我的代碼:
$resultJson = file_get_contents('http://....');
$priceRange = json_decode($resultJson, true);
echo $priceRange['data']['230723']['2019-11-15']['price']; // working
//$priceRange = array_values($priceRange);
echo $priceRange[0][0][0][0]; // not working
第一個回聲有效並返回 52。第二個回聲在有或沒有注釋行的情況下都不起作用(這是重復問題的答案)。
我錯過了什么?
好吧,您知道我希望數據在data
中,如果您不知道下一個鍵,那么reset
會有所幫助。 然后只需獲取所有price
鍵(希望您也知道這一點)並將它們相加:
$result = array_sum(array_column(reset($array['data']), 'price'));
另一種方法是在前兩個級別上使用array_values
:
$result = array_sum(array_column(array_values(array_values($array)[0])[0], 'price'));
要以您嘗試的方式獲得每個價格,您需要:
$result = array_values(array_values(array_values(array_values($array)[0])[0])[0])[0];
無需將數組從關聯更改為數字,只需遍歷現有數組
$sum = 0;
$resultJson = file_get_contents('http://....');
$priceRanges = json_decode($resultJson, true);
foreach ($priceRanges['data'] as $id => $priceRange) {
if (!is_array($priceRange)) {
continue;
}
foreach ($priceRange as $date => $priceInfo) {
$sum += (isset($priceInfo['price']) ? intval($priceInfo['price']) : 0);
}
}
我使用Krzysztof Janiszewski回答編寫的代碼,並且有效。
$sum = 0;
$priceRange = json_decode($resultJson, true);
foreach($priceRange as $item) {
foreach($item as $item2){
foreach($item2 as $item3){
$sum += $item3['price'];
}
}
}
echo $sum;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.