gpt4 book ai didi

php - 如何在 php 中使用 json 获取数组的前 10 个值

转载 作者:可可西里 更新时间:2023-10-31 23:00:36 24 4
gpt4 key购买 nike

这是我的 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 文件。

最佳答案

PHP 需要处理数组,因此使用 json_decode() 将您的 JSON 转换为 PHP 数组.然后您可以使用 array_slice($array, 0, 10); 获取数组中的第 X 个值.

使用 usort()与宇宙飞船运算符(operator) <=> ,您可以对 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);

关于php - 如何在 php 中使用 json 获取数组的前 10 个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56945488/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com