PHP 递归改变二维数组的值的问题
发布网友
发布时间:2022-04-23 23:03
我来回答
共1个回答
热心网友
时间:2023-10-13 01:04
//先来个check方法,得弄方法啊,不然不能递归
public function check($result, $arr, $r) {
$re=$r;
foreach ($result as $value) {
if ($arr[$re]['name'] == $value['name'] || $arr[$re]['uid'] == $value['uid']) {
$re = $re + 1;
$this->check($result, $arr, $re);
}
}
return $re;
}
//以下为主方法
public function xxxxxxxxxxxxxxxx() {
$arr = array(
array('id' => 1, 'name' => 'aaa', 'uid' => 1),
array('id' => 2, 'name' => 'bbb', 'uid' => 2),
array('id' => 3, 'name' => 'ccc', 'uid' => 3),
array('id' => 4, 'name' => 'ddd', 'uid' => 4),
array('id' => 5, 'name' => 'ccc', 'uid' => 3),
array('id' => 6, 'name' => 'bbb', 'uid' => 2),
array('id' => 7, 'name' => 'bbb', 'uid' => 2),
array('id' => 8, 'name' => 'fff', 'uid' => 6),
array('id' => 9, 'name' => 'ccc', 'uid' => 3),
array('id' => 10, 'name' => 'bbb', 'uid' => 2),
array('id' => 11, 'name' => 'ddd', 'uid' => 4),
array('id' => 12, 'name' => 'eee', 'uid' => 5),
array('id' => 13, 'name' => 'fff', 'uid' => 6),
);
$result = array();
for ($i = 1; $i <= 5; $i++) {
$r = $i * 2;
$r = $r -2;
$r = $this->check($result, $arr, $r);
$result[] = $arr[$r];
}
var_mp($result);
}
输出结果为
array (size=5)
0 =>
array (size=3)
'id' => int 1
'name' => string 'aaa' (length=3)
'uid' => int 1
1 =>
array (size=3)
'id' => int 3
'name' => string 'ccc' (length=3)
'uid' => int 3
2 =>
array (size=3)
'id' => int 6
'name' => string 'bbb' (length=3)
'uid' => int 2
3 =>
array (size=3)
'id' => int 8
'name' => string 'fff' (length=3)
'uid' => int 6
4 =>
array (size=3)
'id' => int 11
'name' => string 'ddd' (length=3)
'uid' => int 4
(我午饭没吃帮你弄这个,真够闲的,采纳不采纳看着办)