Reputation: 145
I want to remove only key from multidimensional associative array preserving its value in PHP.
I've tried with foreach loop.
foreach($collections as $k=>$v){
foreach($v as $k1=>$v1){
foreach($v1 as $k2=>$v2){
if($k2 == 'attr_id'){
unset($collections[$k][$k1][$k2]);
}
}
}
}
I've an array like below:
$collections = [
0 => [
0 => [
"attr_id" => 23,
"value" => "Single Side"
],
1 => [
"attr_id" => 23,
"value" => "Double Side"
],
],
1 => [
0 => [
"attr_id" => 31,
"value" => "A4"
],
1 => [
"attr_id" => 31,
"value" => "12x18"
],
2 => [
"attr_id" => 31,
"value" => "B5"
],
3 => [
"attr_id" => 31,
"value" => "A5"
]
]
];
And I want output Like this:
$collections = [
23 => [ "Single Side", "Double Side" ],
31 => [ "A4", "12x18", "B5", "A5" ]
];
Please Help!
Upvotes: 1
Views: 1146
Reputation: 54831
Short solution:
$expected = [];
foreach ($collections as $collection) {
$expected[$collection[0]['attr_id']] = array_column($collection, 'value');
}
Upvotes: 2
Reputation: 38502
You can do this with simply using two foreach()
loop and push the value to attr_id
$expected = [];
foreach($collections as $k=>$v){
foreach($v as $k1=>$v1){
$expected[$v1['attr_id']][] = $v1['value'];
}
}
print_r($expected);
Output:
Array (
[23] => Array (
[0] => Single Side
[1] => Double Side
)
[31] => Array (
[0] => A4
[1] => 12x18
[2] => B5
[3] => A5
)
)
DEMO: https://3v4l.org/JlsIl
Upvotes: 1
Reputation: 22490
Do with array_values
and array_reduce
attr_id
matching$res = call_user_func_array('array_merge',array_values($arr));
$res = array_reduce($res,function($a,$b){
$a[$b['attr_id']] = isset($a[$b['attr_id']]) ? $a[$b['attr_id']] : [] ;
array_push($a[$b['attr_id']],$b['value']);
return $a;
},[]);
print_r($res);
Upvotes: 0