使用PHP从包含列表的JSON对象中获取具有max(value)的列表项的最佳方法
这看起来有点复杂,但实际上并没有那么糟糕。我有一个JSON对象,如下所示:使用PHP从包含列表的JSON对象中获取具有max(value)的列表项的最佳方法,php,json,dictionary,associative-array,Php,Json,Dictionary,Associative Array,这看起来有点复杂,但实际上并没有那么糟糕。我有一个JSON对象,如下所示: {'result': [{'label': {'field1': 'value1', 'field2': 'value2', 'field3': 'value3'}, 'names': {'field1': 'value4', 'field2': 'value
{'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
是词典列表。每个这样的词典
都有3个键,标签
,名称
,和分数
。为了简单起见,这些键中的每个键的值都是一个包含3个字段的字典,例如field1
、field2
、和field3
。结果中可以有任意数量的列表(但通常少于10个)。我想获得具有最大值的列表(及其后续项)。这些值的范围在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'];
}
}
有更好的方法吗?在我看来,这里没有太多的改进空间,但这样你可以节省一微秒:
$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'];
无论哪种方式,如果不遍历所有值,就无法找到最大值 我也这么想。。。我更喜欢Python,当我不得不用PHP做这件事时,我很讨厌它。