utilizing functional helpers
By using array_map
and array_combine
, you can skip having to handle things like counts, iterators, manual array assignment, and manual array combining.
This solution reduces complexity by using procedures which hide all that complexity behind useful, functional APIs.
$names = ['a', 'b', 'c'];
$types = ['$', '%', '^'];
$prices = [1, 2, 3];
$result = array_map(function ($name, $type, $price) {
return array_combine(
['name', 'type', 'price'],
[$name, $type, $price]
);
}, $names, $types, $prices);
echo json_encode($result, JSON_PRETTY_PRINT);
Output (some line-breaks removed for brevity)
[
{"name": "a", "type": "$", "price": 1},
{"name": "b", "type": "%", "price": 2},
{"name": "c", "type": "^", "price": 3}
]
hiding your own complexity
You can even abstract away your own complexity by defining your own procedure, array_zip_combine
— which works like array_combine
but accepts multiple input arrays which are first "zipped" before being combined
this solution requires PHP 7+
// PHP 7 offers rest parameter and splat operator to easily apply variadic function
function array_zip_combine (array $keys, ...$arrs) {
return array_map(function (...$values) use ($keys) {
return array_combine($keys, $values);
}, ...$arrs);
}
$result = array_zip_combine(['name', 'type', 'price'], $names, $types, $prices);
same solution for PHP 5.4+
// PHP 5 doesn't offer splat operator so we have to use
// call_user_func_array to apply a variadic function
function array_zip_combine (array $keys /* args */) {
$f = function () use ($keys) { return array_combine($keys, func_get_args()); };
return call_user_func_array(
'array_map',
array_merge([$f], array_slice(func_get_args(), 1))
);
}
$result = array_zip_combine(['name', 'type', 'price'], $names, $types, $prices);