array combine three or more arrays with php
Personally for readability I would do it this way:
$keys = array('u1','u2','u3');
$names = array('Bob','Fred','Joe');
$emails = array('bob@mail.com','fred@mail.com','joe@mail.com');
$ids = array(1,2,3);
$result = array();
foreach ($keys as $id => $key) {
$result[$key] = array(
'name' => $names[$id],
'email' => $emails[$id],
'id' => $ids[$id],
);
}
Combine and transpose three arrays with associative keys
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);
Is there a way to combine more than two arrays just like array_combine does?
Use array_merge
, to join multiple arrays in PHP.
PHP.net
- array_combine — Creates an array by using one array for keys and another for its values
- array_merge — Merge one or more arrays
Be aware! The behaviour of both is different.
How to combine three arrays without using array_merge or array_combine in php
In PHP 5.6+ You can also use ... when calling functions to unpack an array or
Traversable variable or literal into the argument list:
$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');
array_push($array1, ...$array2, ...$array3);
echo "<pre>";
print_r($array1);
echo "</pre>";
demo
Merge values from multiple arrays in PHP
Use array_merge()
to combine arrays, not array_push()
.
Remove the duplicates at the end after merging everything.
$json = $this->curl_get_marketplace_contents();
$data = json_decode($json, true);
$categories = array();
foreach ($data['themes'] as $theme) {
$array = explode(",", $theme['categories']);
$array = array_map('trim', $array);
$categories = array_merge($array, $categories);
};
return array_unique($categories);
Merging 3 arrays in PHP
Simply foreach over the first array and use the index as the key to the other arrays.
foreach ( $array1 as $idx => $val ) {
$all_array[] = [ $val, $array2[$idx], $array3[$idx] ];
}
Remember this will only work if all 3 arrays are the same length, you might like to check that first
how to merging multiple key and values in PHP
Direct Output
If you just need to output your array directly to the page, you could do something like this:
foreach($original_array['category_id'] as $key => $categoryid) {
$product = $original_array['product'][$key];
$category = $original_array['category'][$key];
echo "{$categoryid} , {$product} , {$category}\n";
}
This is pretty simple and only requires a single foreach loop. This is useful if you do not need to use this data multiple times in different places.
Formatted Array Output
If you may need to use this later in code, I would create a new array with the data in the loop above.
This is probably overkill if you don't ever need to access this data again.
$output = [];
foreach($original_array['category_id'] as $key => $categoryid) {
$product = $original_array['product'][$key];
$category = $original_array['category'][$key];
$output[] = ['category_id' => $categoryid, 'product' => $product, 'category' => $category];
}
This would make $output
be something like
Array
(
[0] => Array
(
[category_id] => 1
[product] => Apple
[category] => Fruit
)
[1] => Array
(
[category_id] => 2
[product] => Cow
[category] => Meat
)
)
Which, of course, is trivial to output in your required format.
foreach($output as $values) {
echo "{$values['categoryid']} , {$values['product']} , {$values['category']}";
}
How to add multiple arrays to a subarray?
This is how you would use array_merge()
<?php
$array1 = array(array("id" => 1, "name" => "world"));
$array2 = array("KM" => 2);
$array3 = array("count" => 1);
print_r(array(array_merge($array1[0], $array2, $array3)));
?>
Which would output:
Array
(
[0] => Array
(
[id] => 1
[name] => world
[KM] => 2
[count] => 1
)
)
Related Topics
How to Get Date from Excel Using PHPexcel Library
PHP Import Excel into Database (Xls & Xlsx)
How to Redirect to Different Url Based on Roles in Symfony 2
How to Enable Ssl in Wamp Server
How to Allow Remote Access to My Wamp Server for Mobile(Android)
How to Call a Static Method from a Class If All I Have Is a String of the Class Name
MySQL Innodb Engine in Laravel
How to Use Laravel Passport with Password Grant Tokens
Fix iOS Picture Orientation After Upload PHP
In PHP, How to Call a Function Interpolated in String
Wordpress Woocommerce - Use Update_Post_Meta to Add Product Attributes
PHP Replaces Spaces with Underscores
MySQL Table Does Not Exist Error, But It Does Exist
Laravel Says "Route Not Defined"