PHP 数据映射

PHP Data Mapping

我得到了一些数据集,必须对其进行映射,对重复项进行分组,如下所示:

我有:

<?php
$var = array(
    array("Name" => "Alfred", "Number" => 1),
    array("Name" => "Alfred", "Number" => 2),
    array("Name" => "Alfred", "Number" => 3),
    array("Name" => "Aethelstan", "Number" => 4),
    array("Name" => "Aethelstan", "Number" => 5),
    array("Name" => "Aethelstan", "Number" => 6),
)
?>

我想改成:

<?php
$var = array(
    array("name" => "Alfred","Number" => array(1,2,3)),
    array("name" => "Aelthestan","Number" => array(4,5,6)),
)
?>

没有大量循环和逐一比较,有人有什么想法吗?

希望这会奏效。

PHP code demo

<?php
$var = array(
    array("Name" => "Alfred", "Number" => 1),
    array("Name" => "Alfred", "Number" => 2),
    array("Name" => "Alfred", "Number" => 3),
    array("Name" => "Aethelstan", "Number" => 4),
    array("Name" => "Aethelstan", "Number" => 5),
    array("Name" => "Aethelstan", "Number" => 6),
);
$result=array();
foreach($var as $value)
{
    if(!isset($result[$value["Name"]]))
    {
        $result[$value["Name"]]=array("Name"=>$value["Name"],"Number"=>array($value["Number"]));
    }
    else
    {
        $result[$value["Name"]]["Number"][]=$value["Number"];
    }

}
$result=array_values($result);
print_r($result);

输出:

Array
(
    [0] => Array
        (
            [Name] => Alfred
            [Number] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 3
                )

        )

    [1] => Array
        (
            [Name] => Aethelstan
            [Number] => Array
                (
                    [0] => 4
                    [1] => 5
                    [2] => 6
                )

        )

)

可能的解决方案:

<?php
$var = array(
    array("Name" => "Alfred", "Number" => 1),
    array("Name" => "Alfred", "Number" => 2),
    array("Name" => "Alfred", "Number" => 3),
    array("Name" => "Aethelstan", "Number" => 4),
    array("Name" => "Aethelstan", "Number" => 5),
    array("Name" => "Aethelstan", "Number" => 6),
);

$result = [];
foreach ($var as $key => $value) {
    if (!isset($result[$value['Name']])) {
        $result[$value['Name']] =[];
    }
    $result[$value['Name']][] = $value['Number'];
}

$final_result = [];
foreach ($result as $key => $value) {
    $final_result[] = ["name" => $key, "number" => $value];
}

print_r($final_result);

您还可以查看 array_reduce 以获得更 functional/declarative/immutable 的方法:

<?php

$flatData = [
  ['name' => 'foo', 'number' => 1],
  ['name' => 'foo', 'number' => 2],
  ['name' => 'foo', 'number' => 3],
  ['name' => 'bar', 'number' => 4],
  ['name' => 'bar', 'number' => 5],
  ['name' => 'bar', 'number' => 6],
];

$treeData = array_reduce($flatData, function ($tree, $data) {
  $key = $data['name'];

  if (empty($tree[$key])) {
    $tree[$key] = $data;
    unset($tree[$key]['number']);
  }

  $tree[$key]['numbers'][] = $data['number'];

  return $tree;
}, []);

print_r($treeData);

https://repl.it/G4Cg