首页 > 解决方案 > 使用 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 个键,labelname, 和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'];
                }
        }

有一个更好的方法吗?

标签: phpjsondictionaryassociative-array

解决方案


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'];

无论哪种方式,如果不遍历所有值,您都无法找到最大值。


推荐阅读