我有一个查询返回数千个带有联系信息的数组。每个都有一个与之关联的用户ID(IndvID)。我需要将具有匹配用户ID的数组连接到多维数组中。
所以这个:
Array
(
[EmailID] => 1
[IndvID] => 78
[EmailType] => Business
[Preferred] => false
[Email] => theiremail@something.com
[Listed] => true
[!diffgr:id] => dbs71
[!msdata:rowOrder] => 0
)
Array
(
[EmailID] => 2
[IndvID] => 78
[EmailType] => Personal
[Preferred] => true
[Email] => theiremail@something.com
[Listed] => true
[!diffgr:id] => dbs72
[!msdata:rowOrder] => 1
)
Array
(
[EmailID] => 3
[IndvID] => 85
[EmailType] => Personal
[Preferred] => true
[Email] => theiremail@something.com
[Listed] => true
[!diffgr:id] => dbs73
[!msdata:rowOrder] => 2
)
Array
(
[EmailID] => 4
[IndvID] => 86
[EmailType] => Personal
[Preferred] => true
[Email] => theiremail@something.com
[Listed] => true
[!diffgr:id] => dbs74
[!msdata:rowOrder] => 3
)
变为
array[0](
Array[0]
(
[EmailID] => 1
[IndvID] => 78
[EmailType] => Business
[Preferred] => false
[Email] => theiremail@something.com
[Listed] => true
[!diffgr:id] => dbs71
[!msdata:rowOrder] => 0
)
Array[1]
(
[EmailID] => 2
[IndvID] => 78
[EmailType] => Personal
[Preferred] => true
[Email] => theiremail@something.com
[Listed] => true
[!diffgr:id] => dbs72
[!msdata:rowOrder] => 1
)
)
Array[1]
(
[EmailID] => 3
[IndvID] => 85
[EmailType] => Personal
[Preferred] => true
[Email] => theiremail@something.com
[Listed] => true
[!diffgr:id] => dbs73
[!msdata:rowOrder] => 2
)
Array[2]
(
[EmailID] => 4
[IndvID] => 86
[EmailType] => Personal
[Preferred] => true
[Email] => theiremail@something.com
[Listed] => true
[!diffgr:id] => dbs74
[!msdata:rowOrder] => 3
)
与" IndvID"
相互匹配答案 0 :(得分:1)
这是一种方式。使用值IndvID
作为键创建结果,然后使用子数组。如果要重新排序主索引,请使用array_values
:
$result = array();
foreach($array as $values) {
$result[$values['IndvID']][] = $values;
}
// if you want to reset the keys
$result = array_values($result);
答案 1 :(得分:0)
非常直接的做法,我已经将聚合数组的关键字设为IndvID,以使事情变得更简单,如果不行,请告诉我,我会调整答案
function add_to_array(array $array, & $aggregated_array)
{
if ( ! isset($array['IndvID']))
return false;
$aggregated_array[$array['IndvID']][] = $array;
}
$aggregated_array = array();
// Run query here...
// I'm assuming mysqli here as it's what I mostly use, substitute as necessary
while ($row = $result->fetch_assoc())
{
add_to_array($row, $aggregated_array);
}
print_r($aggregated_array);