[英]Best way to get list item with max(value) from a JSON object containing lists using PHP
這看起來有點令人費解,但實際上並沒有那么糟糕。 我有一個看起來像這樣的 JSON object:
{'result': [{'label': {'field1': 'value1',
'field2': 'value2',
'field3': 'value3'},
'names': {'field1': 'value4',
'field2': 'value5',
'field3': 'value6'},
'score': {'field1': 0.9336825,
'field2': 0.9711186,
'field3': 0.7606185}},
{'label': {'field1': 'value7',
'field2': 'value8',
'field3': 'value9'},
'names': {'field1': 'value10',
'field2': 'value11',
'field3': 'value12'},
'score': {'field1': 0.9336825,
'field2': 0.9711186,
'field3': 0.13707103}}]}
result
是一個字典列表。 每個這樣的dictionary
都有 3 個鍵, label
、 name
和score
。 這些鍵中的每一個的值又是一個具有 3 個字段的字典,為了簡單起見,假設為field1
、 field2
和field3
。 result
中可以有任意數量的列表(通常少於 10 個)。 我想獲取具有最大['score']['field3']
值的列表(及其后續項目)。 這些值介於 0 和 1 之間。我嘗試過的有點天真; 遍歷列表並跟蹤max
分數:
$resp=json_decode($response,TRUE);
$max = -9.99;
foreach ($resp['result'] as $item)
{
if ($item['score']['field3'] > $max)
{
$max = $item['score']['field3'];
$product_code = $item['label']['field1'];
$product_name = $item['names']['field1'];
$product_score = $item['score']['field1'];
$topic_code = $item['label']['field2'];
$topic_name = $item['names']['field2'];
$topic_score = $item['score']['field2'];
$intent_code = $item['label']['field3'];
$intent_name = $item['names']['field3'];
$intent_score = $item['score']['field3'];
}
}
有一個更好的方法嗎?
IMO 這里沒有太大的改進空間,但是您可以通過這種方式減少一微秒:
$resp=json_decode($response,TRUE);
$max = -9.99;
$maxItem = [];
foreach ($resp['result'] as $item)
{
if ($item['score']['field3'] > $max)
{
$max = $item['score']['field3'];
$maxItem = $item;
}
}
$product_code = $maxItem['label']['field1'];
$product_name = $maxItem['names']['field1'];
$product_score = $maxItem['score']['field1'];
$topic_code = $maxItem['label']['field2'];
$topic_name = $maxItem['names']['field2'];
$topic_score = $maxItem['score']['field2'];
$intent_code = $maxItem['label']['field3'];
$intent_name = $maxItem['names']['field3'];
$intent_score = $maxItem['score']['field3'];
無論哪種方式,如果不遍歷所有值,您都無法找到最大值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.