массивы — 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)),
)
?>

У кого-то есть идеи без множества циклов и сравнений один за другим?

0

Решение

Надеюсь, это сработает.

Демонстрация кода PHP

<?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
)

)

)
1

Другие решения

Вы также можете взглянуть на array_reduce для более функционального / декларативного / неизменного подхода:

<?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

1

Может быть возможным решением:

<?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);
-1
По вопросам рекламы [email protected]