Sandro Togonidze Sandro Togonidze - 1 month ago 10
PHP Question

Combine array values on another array keys in php

I'm having specific problem, I've got 2 arrays:

One, which extracts specific fields from order data, it iterates and extracts id, title, amount and price as many times as many products are on current order, so it looks like this:

$array1 = array( 'id_1' => '2975', 'title_1' => 'first_title', 'amount_1' => '1', 'price_1' => 55, 'id_2' => '2973', 'title_2' => 'second_title', 'amount_2' => '1', 'price_2' => 95, )


There are 2 products on order, if there were 3 there would be another set of values, so I have another array, to which I'd like to map the values, it should be exatly in this form(it's transferred to another website so it only receives data in this form):

$products = Array(

Array
(
'id' => 'first_id',
'title' => 'first_title',
'amount' => 'first_amount',
'price' => 'first_price',
'type' => 0,
'installmenttype' => 0
),

Array
(
'id' => 'second_id',
'title' => 'second_title',
'amount' => 'second_amount',
'price' => 'second_price',
'type' => 0,
'installmenttype' => 0
)


);

I need to map first four values for each sub array in $products variable, and I also need to have as many sub arrays as many products are in current order, it should work like first array in that regard.

I looked through this question:
create multidimensional array using a foreach loop

But couldn't quite get there, so how should the code that achieves that look like?

Answer Source

Define the keys that you want in the output array.

$keys = ['id', 'title', 'amount', 'price', 'type', 'installmenttype'];

Then map array_combine over 4-count chunks of your original array.

$products = array_map(function($product) use ($keys) {
    return array_combine($keys, array_merge($product, [0,0]));
}, array_chunk($array1, 4));

(array_merge adds the zero values for the extra keys so that array_combine can be used.)