我需要一个帮助。我正在使用键值排序数组,我需要一个键值相同然后它应该按字母顺序再次出现。让我解释下面的代码。
{"data":[
{"subcat_id":"9","subcat_name":"SUSHI","order":"9"},
{"subcat_id":"20","subcat_name":"APPETIZERS","order":"6"},
{"subcat_id":"6","subcat_name":"CHINESE","order":"4"},
{"subcat_id":"26","subcat_name":"BRUNCH","order":"4"},
{"subcat_id":"17","subcat_name":"ENTREES","order":"3"},
{"subcat_id":"25","subcat_name":"HAPPY HOUR","order":"2"}
]}
如果订单价值相同(lets say-order->4
),那么它应按照subcat_name
(BRUNCH,CHINESE
)的字母顺序排列。
答案 0 :(得分:0)
您必须按订单ID创建组,然后对它们进行排序。
$json = '{"data":[
{"subcat_id":"9","subcat_name":"SUSHI","order":"9"},
{"subcat_id":"20","subcat_name":"APPETIZERS","order":"6"},
{"subcat_id":"6","subcat_name":"CHINESE","order":"4"},
{"subcat_id":"26","subcat_name":"BRUNCH","order":"4"},
{"subcat_id":"17","subcat_name":"ENTREES","order":"3"},
{"subcat_id":"25","subcat_name":"HAPPY HOUR","order":"2"}
]}';
$data = json_decode($json);
$ordersGroups = array();
foreach ($data->data as $orderData) {
if (!isset($ordersGroups[$orderData->order])) {
$ordersGroups[$orderData->order] = array($orderData);
} else {
$ordersGroups[$orderData->order][] = $orderData;
}
}
$ordersGroups = array_map(function ($orders) {
usort($orders, function ($a, $b) {
return strcmp($a->subcat_name, $b->subcat_name);
});
return $orders;
}, $ordersGroups);
$data->data = array_reduce($ordersGroups, function ($carry, $orderGroup) {
return array_merge($carry, $orderGroup);
}, array());
$json = json_encode($data);
答案 1 :(得分:0)
这可能有效:
$array = //decode your JSON as an array here
$innerComparison = function ($v1, $v2) {
return strcmp($v1["subcat_name"],$v2["subcat_name"]);
};
$mainComparison = function ($v1, $v2) use ($innerComparison) {
if ($v1["order"] === $v2["order"]) {
return $innerComparison($v1,$v2);
} else {
return $v1["order"] < $v2["order"]:-1:1;
}
};
usort($array["data"], $mainComparison);
答案 2 :(得分:0)
您可以使用usort()
。假设您的数据存储在$obj
对象中:
usort
(
$obj->data,
function( $a, $b )
{
if( $a->order == $b->order ) return strcmp( $a->subcat_name, $b->subcat_name );
return $a->order - $b->order;
}
);
根据您的要求,在函数排序$obj->data
之上。
的 eval.in demo 强>
usort()
使用自定义函数对数组进行排序,该函数接收数组的两个元素作为参数:如果考虑第一个参数,则返回的函数值必须是小于,等于或大于零的整数分别小于,等于或大于第二个。
在您的情况下,如果->order
键等于,我们会使用strcmp()
根据->subcat_name
返回排序值,否则我们会返回两个->order
值之间的差值。