如何在PHP中使用JSON获取数组的前10个值

时间:2019-07-09 04:44:08

标签: php json

这是我的JSON文件的示例。

{"Variable":"Hello","Variable1":20}, {"Variable":"Hi","Variable1":30},
{"Variable":"How","Variable1":40}, {"Variable":"Who","Variable1":50},
{"Variable":"Where","Variable1":60}, {"Variable":"This","Variable1":100},
{"Variable":"Pork","Variable1":10}, {"Variable":"Creep","Variable1":90},
{"Variable":"Mega Creeps","Variable1":80}, {"Variable":"LOL","Variable1":0},
{"Variable":"ROFL","Variable1":0}, {"Variable":"LMAO","Variable1":0},
{"Variable":"POP","Variable1":0}, {"Variable":"LOVE","Variable1":0},
{"Variable":"PICK","Variable1":0}, {"Variable":"WHIZ","Variable1":0},
{"Variable":"BORED","Variable1":0}, {"Variable":"KILLAH","Variable1":0},
{"Variable":"LOLLING","Variable1":0}, {"Variable":"HALOO  HALOO","Variable1":0}

如何从最高的Variable1数字到最低的数字获得前10名?但是将以相同的格式传递JSON文件。

2 个答案:

答案 0 :(得分:2)

PHP将需要使用数组,因此请使用json_decode()将JSON转换为PHP数组。然后,您可以使用array_slice($array, 0, 10);获得数组中的X个优先值。

usort()与spaceshipoperator <=>配合使用,可以对对象的Variable1属性进行排序。

$json = '[{"Variable":"Hello","Variable1":20}, {"Variable":"Hi","Variable1":30},
            {"Variable":"How","Variable1":40}, {"Variable":"Who","Variable1":50},
            {"Variable":"Where","Variable1":60}, {"Variable":"This","Variable1":100},
            {"Variable":"Pork","Variable1":10}, {"Variable":"Creep","Variable1":90},
            {"Variable":"Mega Creeps","Variable1":80}, {"Variable":"LOL","Variable1":0},
            {"Variable":"ROFL","Variable1":0}, {"Variable":"LMAO","Variable1":0},
            {"Variable":"POP","Variable1":0}, {"Variable":"LOVE","Variable1":0},
            {"Variable":"PICK","Variable1":0}, {"Variable":"WHIZ","Variable1":0},
            {"Variable":"BORED","Variable1":0}, {"Variable":"KILLAH","Variable1":0},
            {"Variable":"LOLLING","Variable1":0}, {"Variable":"HALOO  HALOO","Variable1":0}]';

// Get the JSON to a PHP array
$array = json_decode($json);

// Sort the array
usort($array, function($a, $b) {
    return $b->Variable1 <=> $a->Variable1;
});

// Slice it, getting the first 10 elements
$parts = array_slice($array, 0, 10);

// Encode it back to JSON
echo json_encode($parts);

答案 1 :(得分:2)

首先,我们需要将此JSON转换为数组:

$array = json_decode($json, true)

然后我们必须对数组进行排序以获取前10名:

function sortByOrder($a, $b) {
    return $a['Variable1'] - $b['Variable1'];
}
usort($array, 'sortByOrder');

然后我们进入前10名:

$array = array_slice($array, 0, 10);

然后我们必须转换回JSON:

echo json_encode($array)