简体   繁体   English

复杂的php数组组合(两种不同的结构)

[英]Complex php arrays combine (two different structures)

I don't even know what words to use :) 我什至不知道该用什么词:)

I have this one array: 我有这个数组:

array(
    0 => array(
        'protein' => 'proteiny',
        'total_fat' => 'total faty',
        'carbohydrates' => 'carbohydrates',
        'food_energy' => 'food energy',
...

And another array: 还有另一个数组:

1 => array(
    'protein' => 'grams',
    'total_fat' => 'grams',
    'carbohydrates' => 'grams',
    'food_energy' => 'kcals',
...

And i want to combine them into a new array in this structure: 我想将它们组合成这种结构的新数组:

$newone = array(
        array('slug' => 'protein', 'name' => 'proteiny', 'format' => 'grams'),
        array('slug' => 'total_fat', 'name' => 'total faty', 'format' => 'grams'),
        array('slug' => 'carbohydrates', 'name' => 'carbohydrates', 'format' => 'grams'),
        array('slug' => 'food_energy', 'name' => 'food energy', 'format' => 'kcals'),
    ...

IS there any way to do that? 有什么办法吗?

How about simple foreach loop when $a is the first array and $b is the second as: $a是第一个数组而$b是第二个数组时,简单的foreach循环怎么样:

foreach($a as $k => $e) {
    $res[] = array('slug' => $k, 'name' => $e, 'format' => $b[$k]);
}

Live example: 3v4l 直播示例: 3v4l

You can use array_map() over the array $a with scope use($b) to make the $newone . 您可以在数组$a上使用array_map()和范围use($ b)来制作$newone Example: 例:

$a = array('protein' => 'proteiny', 'total_fat' => 'total faty', 'carbohydrates' => 'carbohydrates', 'food_energy' => 'food energy');
$b = array('protein' => 'grams', 'total_fat' => 'grams', 'carbohydrates' => 'grams', 'food_energy' => 'kcals');

$newone = array_map(function($val, $slug) use ($b) {
    return array('slug' => $slug, 'name' => $val, 'format' => $b[$slug]);
}, $a, array_keys($a));

print_r($newone);

Working demo . 工作演示

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

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