[英]PHP Array sort by criteria
I have this array but I want to sort it by my criteria. 我有这个数组,但我想按我的标准对其进行排序。
I want if "country" and "top" are the same then they heve to be on one place. 我想如果“国家”和“最高”是相同的,那么他们必须处于同一位置。 Slightly below give an example of what I mean.
下面稍微举例说明一下我的意思。
$array = array(
array("city" => "New York", "country" => "USA", "top" => "1"),
array("city" => "London", "country" => "UK", "top" => "1"),
array("city" => "Sofia", "country" => "BG", "top" => "1"),
array("city" => "Belgrad", "country" => "SRB", "top" => "2"),
array("city" => "Varna", "country" => "BG", "top" => "2"),
array("city" => "LA", "country" => "UK", "top" => "1"),
array("city" => "Bat", "country" => "USA", "top" => "1")
);
Here is the array: 这是数组:
Array
(
[0] => Array
(
[city] => New York
[country] => USA
[top] => 1
)
[1] => Array
(
[city] => London
[country] => UK
[top] => 1
)
[2] => Array
(
[city] => Sofia
[country] => BG
[top] => 1
)
[3] => Array
(
[city] => Belgrad
[country] => SRB
[top] => 2
)
[4] => Array
(
[city] => Varna
[country] => BG
[top] => 2
)
[5] => Array
(
[city] => LA
[country] => USA
[top] => 1
)
[6] => Array
(
[city] => Bat
[country] => UK
[top] => 1
)
)
I want this result: 我想要这个结果:
Array
(
[0] => Array
(
[0] => Array
(
[city] => New York
[country] => USA
[top] => 1
)
[1] => Array
(
[city] => LA
[country] => USA
[top] => 1
)
[2] => Array
(
[top_cities] => 2
)
)
[1] => Array
(
[0] => Array
(
[city] => London
[country] => UK
[top] => 1
)
[1] => Array
(
[city] => Bat
[country] => UK
[top] => 1
)
[2] => Array
(
[top_cities] => 2
)
)
[2] => Array
(
[0] => Array
(
[city] => Sofia
[country] => BG
[top] => 1
)
)
[3] => Array
(
[city] => Belgrad
[country] => SRB
[top] => 2
)
[4] => Array
(
[city] => Varna
[country] => BG
[top] => 2
)
)
Criteria(must match): Country Top and count how top have in this array(sum) 条件(必须匹配):国家/地区最高排名,并计算此数组中最高排名(总和)
I will be very grateful if someone give a idea how to handle with this problem. 如果有人给出如何解决此问题的想法,我将非常感激。 Thanks in advance.
提前致谢。
Try the below code. 试试下面的代码。 There is amall modification in the result.
结果有很多修改。 But I believe it will work for you
但我相信它将为您服务
$array = array(
array("city" => "New York", "country" => "USA", "top" => "1"),
array("city" => "London", "country" => "UK", "top" => "1"),
array("city" => "Sofia", "country" => "BG", "top" => "1"),
array("city" => "Belgrad", "country" => "SRB", "top" => "2"),
array("city" => "Varna", "country" => "BG", "top" => "2"),
array("city" => "LA", "country" => "UK", "top" => "1"),
array("city" => "Bat", "country" => "USA", "top" => "1")
);
$newArray = array();
foreach($array as $key => $val){
$newArray[$val['country']][] = $val;
}
print_r($newArray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.