这是我的阵列。
Array
(
[id] => 1
[color] => "White"
[something] => Array
(
[country] => "France"
[city] => "Paris"
)
)
Array
(
[id] => 2
[color] => "Black"
[something] => Array
(
[country] => "Germany"
[city] => "Berlin"
)
)
Array
(
[id] => 2
[color] => "Red"
[something] => Array
(
[country] => "Russia"
[city] => "Moscow"
)
)
我想将具有相同id
值的数组分组。这应该是输出:
[0] => Array
(
[0] => Array
(
[id] => 1
[color] => "White"
[something] => Array
(
[country] => "France"
[city] => "Paris"
)
)
)
[1] => Array
(
[0] => Array
(
[id] => 2
[color] => "Black"
[something] => Array
(
[country] => "Germany"
[city] => "Berlin"
)
)
[1] => Array
(
[id] => 2
[color] => "Red"
[something] => Array
(
[country] => "Russia"
[city] => "Moscow"
)
)
)
我尝试了几十个foreach
语句,但是我无法在同一个数组中获得具有相同id
的数组。它可能与它是一个多维数组的事实有关吗?我应该使用2个嵌套foreach
来获得结果吗?
答案 0 :(得分:1)
使用id作为新数组的键。
$a[$array[id]][] = $array;
答案 1 :(得分:1)
代码:
<?php
$arr = array(
array(
'id' => 1,
'color' => 'white',
'something' => array(
'country' => 'France',
'city' => 'Paris',
),
),
array(
'id' => 2,
'color' => 'Black',
'something' => array(
'country' => 'Germany',
'city' => 'Berlin',
),
),
array(
'id' => 2,
'color' => 'Red',
'something' => array(
'country' => 'Russia',
'city' => 'Moscow',
),
),
);
function groupify($arr) {
$new = array();
foreach ($arr as $item) {
if (!isset($new[$item['id']])) {
$new[$item['id']] = array();
}
$new[$item['id']][] = $item;
}
return $new;
}
print_r(groupify($arr));
结果:
Array
(
[1] => Array
(
[0] => Array
(
[id] => 1
[color] => white
[something] => Array
(
[country] => France
[city] => Paris
)
)
)
[2] => Array
(
[0] => Array
(
[id] => 2
[color] => Black
[something] => Array
(
[country] => Germany
[city] => Berlin
)
)
[1] => Array
(
[id] => 2
[color] => Red
[something] => Array
(
[country] => Russia
[city] => Moscow
)
)
)
)
如果您不想保留密钥,只需在array_values
之前致电return
。
答案 2 :(得分:0)
如果您想使用foreach:
<?php
$return = array();
foreach($array as $key => $innerArray) {
$return[$innerArray['id']][]= $innerArray;
}
现在$ return包含按ID搜索的内容,其中键1和2是您的ID
array(
1 => array(
array(/** **/)
),
2 => array(
array(/** **/),
array(/** **/)
);
);
然后,您可以像这样访问您的群组:
foreach($return as $key => $groupArray) {
// you have the groups here
foreach($groupArray as $id => $singleArray) {
// singleArray contains your id, colour etc
}
}
foreach($return[1] as $groupOne) {
// all arrays with id = 1
}