我有一个数组,并且有一个userID键。我想要的是将userid作为父键。我当前的变量如下:
$data = array(
[0]=>array(
[userID] => 90
[dateLogin] => 23:35:13
[type] => 28
),
[1]=>array(
[userID] => 90
[dateLogin] => 23:35:10
[type] => 29
),
[2]=>array(
[userID] => 91
[dateLogin] => 23:35:13
[type] => 25
),
[3]=>array(
[userID] => 91
[dateLogin] => 23:35:10
[type] => 23
)
)
现在我想实现如下所示的输出,因为你可以看到用户ID,其中90和91成为键,并且里面有数组:
$data = array(
[90]=> array(
[0] => array(
[userID] => 90
[dateLogin] => 23:35:13
[type] => 28
),
[1]=>array(
[userID] => 90
[dateLogin] => 23:35:10
[type] => 29
),
),
[91]=> array(
[0]=>array(
[userID] => 91
[dateLogin] => 23:35:13
[type] => 25
),
[1]=>array(
[userID] => 91
[dateLogin] => 23:35:10
[type] => 23
)
),
)
到目前为止我所做的是:
foreach ($data as $key => $value) {
$data[$value['userID']] = array();
foreach ($value as $k => $v) {
if($v == $value['userID']){
$data[$value['userID']][] = $value;
}
}
}
我现在可以将userID作为键,但其中的数组是错误的。我错了什么?请帮忙。感谢
答案 0 :(得分:0)
不需要内部foreach
,只需要一个就足够了:
$new_data = array();
foreach($data as $value) {
$new_data[$value['userID']][] = $value;
// ^ userID as key ^ another dimension
}