$mp = array(
array('url'=>'www.abc.com','time'=>'1433551154','referral_url'=>'www.pqr.com'),
array('url'=>'www.xyz.com','time'=>'1433551150','referral_url'=>'www.stu.com'),
array('url'=>'www.lmn.com','time'=>'1433551190','referral_url'=>'www.jhi.com'),
array('url'=>'www.rst.com','time'=>'1433551170','referral_url'=>'www.pqr.com')
);
以上是输入数组,我需要按时间排序和按referral_url唯一的输出。
结果将是-
$mp = array(
array('url'=>'www.lmn.com','time'=>'1433551190','referral_url'=>'www.jhi.com'),
array('url'=>'www.rst.com','time'=>'1433551170','referral_url'=>'www.pqr.com'),
array('url'=>'www.lmn.com','time'=>'1433551150','referral_url'=>'www.stu.com'),
);
记住先按时间排序,然后用referral_url删除重复的。
My Code, what i try -
public function unique_sort($arrs, $id) {
$unique_arr = array();
foreach ($arrs AS $arr) {
if (!in_array($arr[$id], $unique_arr)) {
$unique_arr[] = $arr[$id];
}
}
sort($unique_arr);
return $unique_arr;
}
foreach($mp as $key => $row){
$referral_url[$key] = $row['referral_url'];
$time[$key] = $row['time'];
$url[$key] = $row['url'];
}
array_multisort($time, SORT_DESC, $mp);
$sort_arr = $this->unique_sort($mp, 'referral_url');
print_R($uniqueArray);exit;
但是它只会导致我的referral_url-
Array(
[0] => www.jhi.com
[1] => www.pqr.com
[2] => www.stu.com
)
我需要所有如上定义的输出。
请指路。
试试这个
$mp = array(
array('url'=>'www.abc.com','time'=>'1433551154','referral_url'=>'www.pqr.com'),
array('url'=>'www.xyz.com','time'=>'1433551150','referral_url'=>'www.stu.com'),
array('url'=>'www.lmn.com','time'=>'1433551190','referral_url'=>'www.jhi.com'),
array('url'=>'www.rst.com','time'=>'1433551170','referral_url'=>'www.pqr.com')
);
uasort($mp,function($a,$b){
return $b['time'] - $a['time'];
});
foreach($mp as $value){
$hash = $value['referral_url'];
if(!isset($result[$hash])){
$result[$hash] = $value;
}
}
print_r(array_values($result));
解释:
使用uasort
根据时间对数组进行排序,将得到以下数组
Array
(
[2] => Array
(
[url] => www.lmn.com
[time] => 1433551190
[referral_url] => www.jhi.com
)
[3] => Array
(
[url] => www.rst.com
[time] => 1433551170
[referral_url] => www.pqr.com
)
[0] => Array
(
[url] => www.abc.com
[time] => 1433551154
[referral_url] => www.pqr.com
)
[1] => Array
(
[url] => www.xyz.com
[time] => 1433551150
[referral_url] => www.stu.com
)
)
在foreach
循环中使唯一的值的数组 referral_url
将得到以下数组
Array
(
[www.jhi.com] => Array
(
[url] => www.lmn.com
[time] => 1433551190
[referral_url] => www.jhi.com
)
[www.pqr.com] => Array
(
[url] => www.rst.com
[time] => 1433551170
[referral_url] => www.pqr.com
)
[www.stu.com] => Array
(
[url] => www.xyz.com
[time] => 1433551150
[referral_url] => www.stu.com
)
)
最后使用array_values
值只有整数键
小提琴