[英]how to get a slice of a multidimensional array using an array with index keys
I have an array 我有一个数组
$arr = [
[
'id' => 10,
'name' => 'John',
'occupation' => 'engineer',
'points' => 10
],
[
'id' => 10,
'name' => 'John',
'occupation' => 'librarian',
'points' => 14
],
[
'id' => 7,
'name' => 'Sarah',
'occupation' => 'artist',
'points' => 21
],
[
'id' => 7,
'name' => 'Sarah',
'occupation' => 'teacher',
'points' => 17
],
[
'id' => 10,
'name' => 'John',
'occupation' => 'butcher',
'points' => 7
],
[
'id' => 7,
'name' => 'Sarah',
'occupation' => 'engineer',
'points' => 9
],
[
'id' => 25,
'name' => 'Andreea',
'occupation' => 'judge',
'points' => 11
]
];
And I use this built in functions to get unique ids: 我使用此内置函数来获取唯一的ID:
$people = array_column($arr, 'id', 'id');
And then I use a foreach to get every occurrence of each user in the main array $arr
: 然后,我使用一个foreach来获取主数组
$arr
中每个用户的每次出现:
foreach($people as $id){
$keys = array_keys(array_column($arr, 'id'), $id);
}
This is the return: 这是回报:
Array
(
[0] => 0
[1] => 1
[2] => 4
)
Array
(
[0] => 2
[1] => 3
[2] => 5
)
Array
(
[0] => 6
)
Now in order to build a small array for each person I could loop trough this small arrays that contain the keys from the main array and get the values and ending up with small slices. 现在,为了为每个人构建一个小数组,我可以遍历这个包含主数组键的小数组,并获取值并以小片段结尾。
But, how can I get the actual $arr
values for each person instead of getting just the keys? 但是,如何获得每个人的实际
$arr
值,而不仅仅是获得键? (using as little resources as possible) (使用尽可能少的资源)
I need the result to be like this: 我需要的结果是这样的:
Array
(
[10] => Array
(
[0] => Array
(
[id] => 10
[name] => John
[occupation] => engineer
[points] => 10
)
[1] => Array
(
[id] => 10
[name] => John
[occupation] => librarian
[points] => 14
)
[2] => Array
(
[id] => 10
[name] => John
[occupation] => butcher
[points] => 7
)
)
[7] => Array
(
[0] => Array
(
[id] => 7
[name] => Sarah
[occupation] => artist
[points] => 21
)
[1] => Array
(
[id] => 7
[name] => Sarah
[occupation] => teacher
[points] => 17
)
[2] => Array
(
[id] => 7
[name] => Sarah
[occupation] => engineer
[points] => 9
)
)
[25] => Array
(
[0] => Array
(
[id] => 25
[name] => Andreea
[occupation] => judge
[points] => 11
)
)
)
PS: I don't need to keep the key index the same. PS:我不需要保持键索引相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.