1

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?

user315338
  • 67
  • 6

2 Answers2

1

How about simple foreach loop when $a is the first array and $b is the second as:

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

Live example: 3v4l

dWinder
  • 11,597
  • 3
  • 24
  • 39
1

You can use array_map() over the array $a with scope use($b) to make the $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.

MH2K9
  • 11,951
  • 7
  • 32
  • 49