简体   繁体   English

将多维关联数组转置为根据外部关联键排序的多维索引数组

[英]Transpose a multidimensional associative array into a multidimensional indexed array sorted against and an external associative key

I need to transpose a multidimensional associative array into a multidimensional indexed array sorted against and an external associative key.我需要将一个多维关联数组转置为一个多维索引数组和一个外部关联键。 In the example below, I need a way to get from the 'input' to the 'expected output'.在下面的示例中,我需要一种从“输入”到“预期输出”的方法。

I've tried array_match(), array_intersect() but I think I'm missing something.我试过 array_match(), array_intersect() 但我想我错过了一些东西。 There must be an elegant solution to this but I cannot figure it out.必须有一个优雅的解决方案,但我无法弄清楚。

//Input  

  $array = array(
    array('Volvo' => 22, 'BMW' => 13, 'Saab' => 5, 'Land Rover' => 11),
    array('Nissan' => 10, 'Saab' => 4),
    array('Land Rover' => 22, 'BMW' => 9, 'Nissan' => 2, 'Ford' => 17)
    //...
  );

//Expected output  

  $array_cars = array(   // sorted list of unique car names
    0 => 'BMW',
    1 => 'Ford',
    2 => 'Land Rover',
    3 => 'Nissan',
    4 => 'Saab',
    5 => 'Volvo'
    //...
    );

  $compiled_data = array(    // 2D matrix, columns: $array, rows: $array_car
    array(0 => 13, 2 => 9),  // 'BMW'
    array(2 => 17),          // 'Ford'
    array(0 => 11, 2 => 22), // 'Land Rover'
    array(1 => 10, 2 => 2),  // 'Nissan'
    array(0 => 5, 1 => 4),   // 'Saab'
    array(1 => 22)           // 'Volvo'
    //...
);

Probably the simplest thing is to just iterate over all the values, sorting them into a car indexed array.可能最简单的事情就是遍历所有值,将它们排序到汽车索引数组中。 You can then use ksort to sort the data:然后,您可以使用ksort对数据进行排序:

$output = array();
foreach ($array as $key => $a) {
    foreach ($a as $car => $v) {
        $output[$car][$key] = $v;
    }
}
ksort($output);
$array_cars = array_keys($output);
$compiled_data = array_values($output);
var_export($array_cars);
var_export($compiled_data);

Output: Output:

array (
  0 => 'BMW',
  1 => 'Ford',
  2 => 'Land Rover',
  3 => 'Nissan',
  4 => 'Saab',
  5 => 'Volvo',
)
array (
  0 => 
  array (
    0 => 13,
    2 => 9,
  ),
  1 => 
  array (
    2 => 17,
  ),
  2 => 
  array (
    0 => 11,
    2 => 22,
  ),
  3 => 
  array (
    1 => 10,
    2 => 2,
  ),
  4 => 
  array (
    0 => 5,
    1 => 4,
  ),
  5 => 
  array (
    0 => 22,
  ),
)

Demo on 3v4l.org 3v4l.org 上的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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