不太确定我是否理解这个问题,但也许......
您可以对数组进行排序并记住当前的用户 ID,以便您的脚本可以跳过重复项,直到它到达另一个 ID。
<?php
$data = data();
usort(
$data,
function($a,$b) {
return strnatcmp($a->USERID, $b->USERID);
}
);
$current = null;
foreach( $data as $e ) {
if ( $current!=$e->USERID ) {
$current = $e->USERID;
echo $e->USERID, ' ', $e->SUBCATID, "\n";
}
}
function data() {
$x = array(
array(201087,1),
array(201146,1),
array(201087,3),
array(201087,2),
array(222222,3)
);
foreach($x as $y) {
$o = new StdClass;
$o->USERID = $y[0];
$o->SUBCATID = $y[1];
$data[] = $o;
}
return $data;
}
或者脚本会记住所有先前处理的 id,例如在 hashmap/array 中
<?php
$data = data();
$processed = array();
foreach( $data as $e ) {
if ( !isset($processed[$e->USERID]) ) {
$processed[$e->USERID] = true;
echo $e->USERID, ' ', $e->SUBCATID, "\n";
}
}
function data() {
$x = array(
array(201087,1),
array(201146,1),
array(201087,3),
array(201087,2),
array(222222,3)
);
foreach($x as $y) {
$o = new StdClass;
$o->USERID = $y[0];
$o->SUBCATID = $y[1];
$data[] = $o;
}
return $data;
}
两个脚本都打印
201087 1
201146 1
222222 3