php 需要帮助在嵌套数组需要找到第一个相同的元素,并添加他们的第二个元素在一个单一的数组?[已关闭]

zujrkrfu  于 2022-11-28  发布在  PHP
关注(0)|答案(4)|浏览(114)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题吗?**通过editing this post添加详细信息并阐明问题。

3天前关闭。
Improve this question
我有一个数组,其中包含需要重新排列的不同值的数组。

原始数组

$cars = [
  [2022, "Corolla"],
  [2022, "Toyota"],
  [2021, "Corolla"],
  [2021, "Toyota"],
  [2021, "Honda"]
];

必须是数组

$resultCars = [
  [2022, "Corolla", "Toyota"],
  [2021, "Corolla", "Toyota", "Honda"]
];
efzxgjgh

efzxgjgh1#

在JS中:

const Cars = [ [2022, "Corolla"], [2022, "Toyota"], [2021, "Corolla"], [2021, "Toyota"], [2021, "Honda"] ];

const res = Cars.reduce((a, [year, name]) => ((a[year] ??= [year]).push(name),a),{});

console.log(Object.values(res));
von4xj4u

von4xj4u2#

下面是我在Javascript中的实现方式:

ResultCars = Cars.reduce((carry, [year, make]) =>
{
    let item = carry.find(([existingYear]) => existingYear === year);
    if(item)
        item.push(make);
    else
        carry.push([year, make]);

    return(carry);
}, []);
gjmwrych

gjmwrych3#

const cars = [
  [2022, "Corolla"],
  [2022, "Toyota"],
  [2021, "Corolla"],
  [2021, "Toyota"],
  [2021, "Honda"]
];
console.log(Object.entries(cars.reduce((a,[year,make])=>
  ((a[year]??=[]).push(make), a), {})).map(i=>i.flat()))
sulc1iza

sulc1iza4#

下面是C++中的一个方法:

vector<pair<int, string>> cars {
    {2022, "Corolla"},
    {2022, "Toyota"},
    {2021, "Corolla"},
    {2021, "Toyota"},
    {2021, "Honda"}
};

map<int, set<string>> resultCars;
for (const auto& c : cars)
{
    resultCars[c.first].insert(c.second);
}

完整示例(live demo):

#include <iostream>
#include <iterator>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>

using namespace std;

int main()
{
    // Input
    vector<pair<int, string>> cars {
        {2022, "Corolla"},
        {2022, "Toyota"},
        {2021, "Corolla"},
        {2021, "Toyota"},
        {2021, "Honda"}
    };

    // Index
    map<int, set<string>> resultCars;
    for (const auto& c : cars)
    {
        resultCars[c.first].insert(c.second);
    }

    // Output
    for (const auto& c : resultCars)
    {
        int year = c.first;
        const auto& names = c.second;
        cout << year << " : ";
        copy(names.begin(), names.end(), ostream_iterator<string>(cout, " "));
        cout << "\n";
    }
}

相关问题