-1

I have an array as

Array
(
  [0] => Array
      (
          [attribute_pa_weight] => 500g-pack
      )
  [1] => Array
     (
        [attribute_pa_weight] => 1kg-pack
     )

 )

Would need the Output to be

   Array
  (
       [attribute_pa_weight] => Array
    (
        [0] => 500g-pack
        [1] => 1kg-pack
    )
  )

Want the sorting without mentioning the key value to sort because we have the dey coming dynamically.

2 Answers2

1

PHP function array_reduce can be used here:

<?php
$a = [['attribute_pa_weight'=>'500g-pack'],['attribute_pa_weight'=>'1kg-pack']];

$res = array_reduce(
    $a, // source array
    function($acc, $el) {
        if (!isset($acc[key($el)])) $acc[key($el)] = [];
        array_push($acc[key($el)], $el[key($el)]);
        return $acc;
    },
    [] // initial result
);
    
print_r($res);

You can try code at PHPize.online

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
1

Another candidate for this job would be array_map!

$input = [
    ['attribute_pa_weight' => '500g-pack'],
    ['attribute_pa_weight' => '1kg-pack'],
];

$output['attribute_pa_weight'] = array_map(fn ($v) => $v['attribute_pa_weight'], $input);

print_r($output);

If you can't or don't want to use arrow functions (need PHP ^7.4.0).

$output['attribute_pa_weight'] = array_map(function ($value) {
    return $value['attribute_pa_weight'];
}, $input);

print_r($output);

And if you want it dynamic, you could create a function.

$merge = function ($name) use ($input) {
    return [$name => array_map(fn ($v) => $v[$name], $input)];
};

print_r($merge('attribute_pa_weight'));
Ron van der Heijden
  • 14,803
  • 7
  • 58
  • 82
  • OP doesn't mention what sorting is required. You might want to show how to sort the final output. Great job. – ryantxr Sep 18 '20 at 14:41