我有以下数组uid
。我想基于Array (
[0] => Array (
[id] => 1
[pid] => 121
[uid] => 1
)
[1] => Array (
[id] => 2
[pid] => 13
[uid] => 1
)
[2] => Array (
[id] => 5
[pid] => 121
[uid] => 1
)
)
创建最终数组。
如果uid在循环中相同,则会连接值。
Array (
[0] => Array (
[id] => 1,2,5
[pid] => 121,13,121
[uid] => 1
)
)
我想创建最终数组,如..
foreach
我如何使用foreach($uidValues as $r)
{
if(in_array($r['uid'],$finalArray))
{
$finalArray['id'] .= ','.$r['id'];
$finalArray['pid'] .= $r['pid'];
$finalArray['uid'] = ','.$r['uid'];
}
else{
$finalArray[] = array("id" => $r['id'], "pid" => $r['pid'], "uid" => $r['uid']);
}
}
循环来实现它?
我尝试了以下代码..
public aspect Profiler {
pointcut beforeMethod(): !within(Profiler);
before(): beforeMethod() { /* Do something */ }
pointcut afterMethod(): !within(Profiler);
after(): afterMethod() { /* Do something */}
}
答案 0 :(得分:4)
简单地尝试
$result = [];
foreach ($arr as $key => $value) {
$hash = $value['uid'];
if (isset($result[$hash])) {
$result[$hash]['id'] = $result[$hash]['id'] . ',' . $value['id'];
$result[$hash]['pid'] = $result[$hash]['pid'] . ',' . $value['pid'];
$result[$hash]['uid'] = $result[$hash]['uid'] . ',' . $value['uid'];
} else {
$result[$hash]['id'] = $value['id'];
$result[$hash]['pid'] = $value['pid'];
$result[$hash]['uid'] = $value['uid'];
}
}
print_r(array_values($result));
答案 1 :(得分:2)
$before = array(
'0' => array(
'id' => 1,
'pid' => 121,
'uid' => 1,
),
'1' => array(
'id' => 2,
'pid' => 13,
'uid' => 1,
),
'2' => array(
'id' => 5,
'pid' => 121,
'uid' => 1,
),
);
$after = array();
foreach ($before as $row) {
if (array_key_exists($row['uid'], $after)) {
$after[$row['uid']]['id'] .= ',';
$after[$row['uid']]['pid'] .= ',';
} else {
$after[$row['uid']]['uid'] = $row['uid'];
}
$after[$row['uid']]['id'] .= $row['id'];
$after[$row['uid']]['pid'] .= $row['pid'];
}
然后,您可以删除数组键以获得完全相同的数组:
$after = array_values($after);
<强>输出:强>
array (
0 =>
array (
'uid' => 1,
'id' => '1,2,5',
'pid' => '121,13,121',
),
)
答案 2 :(得分:-1)
正如@b0s3在评论中所说:使用uid
作为新数组的关键。
foreach($uidValues as $item) {
$result[$item['uid']]['pid'][] = $item['pid'];
$result[$item['uid']]['id'][] = $item['id'];
}
<强>输出强>:
Array
(
[1] => Array
(
[pid] => Array
(
[0] => 121
[1] => 13
[2] => 121
)
[id] => Array
(
[0] => 1
[1] => 2
[2] => 5
)
)
)