php - 使用 PHP 从包含列表的 JSON 对象中获取具有 max(value) 的列表项的最佳方法
问题描述
这看起来有点令人费解,但实际上并没有那么糟糕。我有一个如下所示的 JSON 对象:
{'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'];
无论哪种方式,如果不遍历所有值,您都无法找到最大值。
推荐阅读
- azure - “命名空间‘Microsoft.Azure’中不存在类型或命名空间名称‘设备’”
- bash - 如何使用包含给定目录中所有文件的参数执行命令?
- sql - 两个表的数据连接 MS Access SQL
- angular - 刷新相同的 URL 会导致 404 在 Angular 中找不到
- anaconda - DLL 加载失败并且找不到模块:我应该重新安装 anaconda 吗?
- python - 在类中导入 python 方法的更简洁的方法
- .net - 将自定义机器密钥添加到 Asp.Net Core 2.2
- sql - SQL - 自动查找包含两列的偏移量
- sql - Postgres sql基于整数在结果中显示特定字符串
- c# - WaitRetryForever 不适用于 Polly.Net Resiliency 中的自定义异常