PHP/Laravel - 从两个简单数组或结合这两个数组的关联数组创建一个对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52671908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:06:11  来源:igfitidea点击:

PHP/Laravel - Create an array of objects from two simple arrays or an associative array that combines that two

phparrayslaravelobjectlaravel-5

提问by Matt Larson

I'm looking for a way transform a php associative array into an array of object and keying each association. I could also treat this as two separate simple arrays, one with the names and one with the classes. Here's an associative example...

我正在寻找一种将 php 关联数组转换为对象数组并键入每个关联的方法。我也可以将其视为两个单独的简单数组,一个带有名称,另一个带有类。这是一个关联的例子......

array:2 [
  "someName" => "someClass"
  "someOtherName" => "someOtherClass"
]

Or

或者

names => [0 => 'name1', 1 => 'name2']
classes => [0 => 'class1', 1 => 'class2']

...either way, I'm looking for an end result like this:

...无论哪种方式,我都在寻找这样的最终结果:

[
    { 'name': 'someName', 'class': 'someClass' },
    { 'name': 'someOtherName', 'class': 'someOtherClass' }
]

What's the smartest way to do this?

做到这一点最聪明的方法是什么?

回答by Marcin Nabia?ek

I think the best way is to combine zipmethod with transformor map:

我认为最好的方法是将zip方法与transformmap结合起来:

$names = [0 => 'name1', 1 => 'name2'];
$classes = [0 => 'class1', 1 => 'class2'];

$merged = collect($names)->zip($classes)->transform(function ($values) {
    return [
        'name' => $values[0],
        'class' => $values[1],
    ];
});

dd($merged->all());

As a result you get array:

结果你得到数组:

array:2 [▼
  0 => array:2 [▼
    "name" => "name1"
    "class" => "class1"
  ]
  1 => array:2 [▼
    "name" => "name2"
    "class" => "class2"
  ]
]

so if you need json, you can just use json_encode($merged)

所以如果你需要json,你可以使用 json_encode($merged)

回答by Christian Gallarmin

This output is the same on your first block.

这个输出在你的第一个块上是一样的。

$array = ['someName' => 'someClass', 'someOtherName'  => 'someOtherClass'];

You can also use laravel collections, provides a fluent, convenient wrapper for working with arrays of data. For example, check out the following code.

您还可以使用 laravel 集合,它为处理数据数组提供了流畅、方便的包装器。例如,查看以下代码。

$collection = collect([
    'names' => [
         ['0' => 'name1', '1' => 'name2'],
     ],
    'classes' => [
         ['0' => 'class1', '2' => 'class2']
     ],
]);

There is also method combine that your looking for, The combinemethod combines the values of the collection, as keys, with the values of another array or collection: Read more info at https://laravel.com/docs/5.7/collections

还有您正在寻找的combine方法组合,该方法将集合的值作为键与另一个数组或集合的值相结合:在https://laravel.com/docs/5.7/collections阅读更多信息