简体   繁体   中英

Remove only Key from Multidimensional Associative Array in PHP

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!

Short solution:

$expected = [];
foreach ($collections as $collection) {
    $expected[$collection[0]['attr_id']] = array_column($collection, 'value');
}

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

Do with array_values and array_reduce

  1. first merge all subArray's to one array
  2. The use reduce to apppend value based with attr_id matching

Sandbox demo

$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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM