Reputation: 26331
Given [1=>[4=>[]],3=>[2=>[]],0=>[6=>[]],8=>[2=>[]]]
, how can I obtain [4,2,6]
? I can obviously use a foreach()
loop, but am interested whether a more concise solution is available.
<?php
$arr1=[
1=>[4=>[]],
3=>[2=>[]],
0=>[6=>[]],
8=>[2=>[]],
];
print_r($arr1);
$arr2=[4,2,6,2];
print_r($arr1);
$arr3=array_values(array_unique($arr2));
print_r($arr3);
Array
(
[1] => Array
(
[4] => Array
(
)
)
[3] => Array
(
[2] => Array
(
)
)
[0] => Array
(
[6] => Array
(
)
)
[8] => Array
(
[2] => Array
(
)
)
)
Array
(
[1] => Array
(
[4] => Array
(
)
)
[3] => Array
(
[2] => Array
(
)
)
[0] => Array
(
[6] => Array
(
)
)
[8] => Array
(
[2] => Array
(
)
)
)
Array
(
[0] => 4
[1] => 2
[2] => 6
)
Upvotes: 1
Views: 39
Reputation: 92904
The shortest one with array_map
and key
functions:
$result = array_unique(array_map(function($a){ return key($a); }, $arr1));
print_r($result);
The output:
Array
(
[1] => 4
[3] => 2
[0] => 6
)
Upvotes: 0
Reputation: 4141
You could probably do something like this:
$arr1=[
1=>[4=>[]],
3=>[2=>[]],
0=>[6=>[]],
8=>[2=>[]],
];
$arr2 = array_unique(array_reduce($arr1, function ($a, $b) {
$a = array_merge($a, array_keys($b));
return $a;
}, []));
print_r($arr2);
This is similar to the solution proposed in the first comment but this one will also work when you have more than one items in the inner arrays
Upvotes: 1