PHP combine multiple array into one with key - php

I am lost actually, not sure how to explain the question.
Suppose I have three array
$name = array('mark', 'jones', 'alex');
$age = array(12, 23, 34);
$country = array('USA', 'UK', 'Canada');
What I am looking for is:
array(
0 => array(
'name' => 'mark',
'age' => 12,
'country' => 'USA'
)
1 => array(
'name' => 'jones',
'age' => 23,
'country' => 'UK'
)
2 => array(
'name' => 'alex',
'age' => 34,
'country' => 'Canada'
);
Couldn't figure out any built in PHP array function to handle it.

try something like this
$result = array();
foreach($name as $key => $value)
{
$result[$key] = array (
'name' => $value,
'age' => $age[$key],
'country' => $country[$key]
);
}
echo '<pre>';
print_r($result);
?>

You could do it without any manual looping like this:
// array_map with null callback merges corresponding items from each input
$merged = array_map(null, $name, $age, $country);
// walk over the results to change array_map's numeric keys to strings
$keys = ['name', 'age', 'country'];
array_walk(
$merged,
function(&$row) { $row = array_combine(['name', 'age', 'country'], $row); }
);
print_r($merged);
You can even write it in such a way that the keys in the result are equal to the names of the variables $name, $age, $country without needing to repeat yourself:
// Here "name", "age" and "country" appear only once:
$inputs = compact('name', 'age', 'country');
$merged = call_user_func_array('array_map', [null] + $inputs);
$keys = array_keys($inputs);
array_walk(
$merged,
function(&$row) use($keys) { $row = array_combine($keys, $row); }
);
However, to be frank it might be more readable (and it might even be faster) to just for over the inputs (assuming they have the same number of items) and do it manually.

Related

Check if the value of a key in one array is equal to the value of different key in another array

I have 2 multidimensional arrays and I want to get the 1st array where the value of [file] key in array 1 is equal to value of [folder_name] key in array 2
$arr1 = [
[
'is_dir' => '1',
'file' => 'hello member',
'file_lcase' => 'hello member',
'date' => '1550733362',
'size' => '0',
'permissions' => '',
'extension' => 'dir',
],
[
'is_dir' => '1',
'file' => 'in in test',
'file_lcase' => 'in in test',
'date' => '1550730845',
'size' => '0',
'permissions' => '',
'extension' => 'dir',
]
];
$arr2 = [
[
'dic_id' => '64',
'folder_name' => 'hello member',
'share_with' => '11',
],
[
'dic_id' => '65',
'folder_name' => 'hello inside',
'share_with' => '11',
],
[
'dic_id' => '66',
'folder_name' => 'in in test',
'share_with' => '11',
],
];
I have tried while looping 2 arrays and getting to one array but it is not success.
We can iterate both arrays inside each other to check until we have a match.
Please be aware that this shows only the first match. If you want to keep all matches you should use another helper array to store first array values that matches to second array.
foreach ($array1 as $key => $value) {
foreach ($array2 as $id => $item) {
if($value['file'] == $item['folder_name']){
// we have a match so we print out the first array element
print_r($array1[$key]);
break;
}
}
}
To avoid a double loop that gives a time complexity of O(n²), you could first create the set of "folder_name" values (as keys), and then use that to filter the first array. Both these operations have a time complexity of O(n) which is certainly more efficient for larger arrays:
$result = [];
$set = array_flip(array_column($arr2, "folder_name"));
foreach ($arr1 as $elem) {
if (isset($set[$elem["file"]])) $result[] = $elem;
}
$result will have the elements of $arr1 that meet the requirement.
$arr1 = array();
$arr2 = array();
$arr3 = array();
$arr1[] = array('is_dir'=>'1','file'=>'hello member','file_lcase'=>'hello member','date'=>'1550733362','size'=>'0','permissions'=>'','extension'=>'dir');
$arr1[] = array('is_dir'=>'1','file'=>'in in test','file_lcase'=>'in in test','date'=>'1550730845','size'=>'0','permissions'=>'','extension'=>'dir');
$arr2[] = array('dic_id'=>'64','folder_name'=>'hello member','share_with'=>'11');
$arr2[] = array('dic_id'=>'65','folder_name'=>'hello member','share_with'=>'11');
$arr2[] = array('dic_id'=>'66','folder_name'=>'in in test','share_with'=>'11');
foreach($arr1 as $a){
foreach($arr2 as $a2){
if($a['file'] == $a2['folder_name']){
$arr3[]=$a;
}
}
}
$arr3 = array_map("unserialize", array_unique(array_map("serialize", $arr3))); // remove duplicates
var_dump($arr3);
$arr3 contains the resultant array.

make an Array from 2 Arrays

I have this:
$Array1 = "FirstName, LastName, Email";
$Array2 = "John, Doe, johndoe#email.com";
Using a foreach or other means, Could the final array format to look like this?
$mergedArrays = array(
'FirstName' =>"John",
'LastName' => "Doe",
'Email' =>'johndoe#email.com',
);
print_r($mergedArrays);
If you are sure that both array will contain the same number separeted by comma, use this:
Version 1 (testing with 100000 takes ~0.08s, +-4x faster)
<?php
$Array1 = "FirstName, LastName, Email";
$Array2 = "John, Doe, johndoe#email.com";
$Array1 = explode(',', preg_replace('/\s*,\s*/',',',$Array1)); //remove spaces before and after comma
$Array2 = explode(',', preg_replace('/\s*,\s*/',',',$Array2));
if(count($Array1) == count($Array2)) {
$result = array_combine($Array1, $Array2);
}
print_r($result);
Output:
Array (
[FirstName] => John
[LastName] => Doe
[Email] => johndoe#email.com
)
Alternative version from #castis (testing with 100000 takes ~0.3s)
$Array1 = explode(',',$Array1);
$Array2 = explode(',',$Array2);
$result = array_combine(array_map('trim', $Array1), array_map('trim', $Array2));
If you must use a foreach (where array_combine would do):
<?php
$fields = ['FirstName', 'LastName', 'Email'];
$values = ['John', 'Doe', 'johndoe#email.com'];
foreach($fields as $k => $field)
$result[$field] = $values[$k];
var_export($result);
Output:
array (
'FirstName' => 'John',
'LastName' => 'Doe',
'Email' => 'johndoe#email.com',
)

PHP - How to check two arrays and search for matching keys and merge the values

How to check two arrays and search for matching keys and merge the values of the 1st array with the matching keys of the second array.Please help me as I'm new to this.
example :
1st array = {id => 11,name => 'name',age => 18 }
2nd array = {id,name,age,school}
I want to get the result by adding the matching values to the 2nd array
2nd array = {id => 11,name => 'name',age => 18,school => }
try this
$a = ['id' => 11,'name' => 'name','age' => 18];
$b = array_flip(['id','name','age','school']);
foreach($b as $key => &$value){
$value = '';
}
$result = array_merge($b, $a);
One of the simple way is looping
$first= array('id' => 11,'name' => 'name','age' => 18 );
$second = array('id','name','age','school');
foreach ($second as $value) {
if(isset($first[$value])){
$final[$value] = $first[$value];
}
};
print_r($final);
Second Array flip and array merge
$first = ['id' => 11,'name' => 'name','age' => 18];
$second= array_flip(['id','name','age','school']);
foreach($second as $key => s$value){
$value = '';
}
$result = array_merge($second, $first);
print_r($result);
Use array_merge
<?php
$array1 = array('id' => '11', 'name' => 'name', 'age' => 18);
$array2 = array('id','name','age','school');
$array3 = array_merge(array_fill_keys($array2, null), $array1);
print_r($array3);
?>

Throw away whole array but the first item

Assume I have the following array:
$array(
'32' => array('name' => 'paul', 'age' => 43),
'17' => array('name' => 'eric', 'age' => 19),
'99' => array('name' => 'dave', 'age' => 65)
)
I am only interested in the first $array item:
$array2 = array('key'=> 32, 'name' => 'paul', 'age' => 43)
What is the most efficient way to accomplish this? In other words, can I throw out all other items of $array with one command?
Use array_shift().
array_shift() shifts the first value of the array off and returns it,
shortening the array by one element and moving everything down. All
numerical array keys will be modified to start counting from zero
while literal keys won't be touched.
$array2 = array_shift($array);
This means that $array2 now holds the first element, while $array holds the rest of the elements.
try this
$array2 = array_shift($array);
$newArr = reset($array);
I think there is no problem with that.
There are 2 options, really. Either you can just select the first item in the array
$array2 = $array[0];
Or you could use array_slice as
$array2 = array_slice($array, 0, 1);
Array_shift is probably the best way. But just for fun here is another way.
$first_element = end(array_reverse($array));
$k = array_merge(array('key' => key($array)), array_shift($array));
Returns in the specified format.
key gets you the first key, array_shift gets you the first value, and merge using array_merge
resetting an array also returns the first element (end() returns the last):
$first = reset( $array );
http://www.php.net/manual/en/function.reset.php
But to generate the exact result you want, you could write something like this
foreach( $array as $k => $first ){ // get first sub-array and its key
$first['key'] = $k; // add the key
break; // we don't care about the other elements, goodbye
}
Futuregeek's method fixed:
$first =
// returns first element, and sets it as the current element for key()
reset( $array )
// instead of array_merge, (sometimes) you can use the + operator
+
// key() will return the appropriate key after reset()
array('key' => key( $array ));
Try It :
$arr = array(
'32' => array('name' => 'paul', 'age' => 43),
'17' => array('name' => 'eric', 'age' => 19),
'99' => array('name' => 'dave', 'age' => 65)
);
foreach($arr as $key => $value)
{
$result[$key] = $value;
break;
}
print_r($result);
##-------Secount Way If you don't want Key 32--------------------------
$arr = array(
'32' => array('name' => 'paul', 'age' => 43),
'17' => array('name' => 'eric', 'age' => 19),
'99' => array('name' => 'dave', 'age' => 65)
);
$arr = array_reverse($arr);
print_r(end($arr));
#------ Third Way If you don't want Key 32 -------------
echo "<br>=======<br>";
$arr = array(
'32' => array('name' => 'paul', 'age' => 43),
'17' => array('name' => 'eric', 'age' => 19),
'99' => array('name' => 'dave', 'age' => 65)
);
$array2 = array_shift($arr);
print_r($array2);

how combine multiple arrays into a single associate array using the arrays as keys

I have 2 arrays that i would like to loop through and combine into an associative array. I would like to use the 2 arrays as the keys for the new associative array. I am new to php so any and all help would be appreciated.
$id = array( 2, 4);
$qty = array( 5, 7);
array('id' => , 'qty' => );
Thanks in advance
I would like to output something like this
array(
'id' => 2,
'qty' => 5),
array(
'id'=> 4,
'qty' => 7
)
You can do:
$result = array();
for($i=0;$i<count($id);$i++) {
$result[] = array('id' => $id[$i], 'qty' => $qty[$i]);
}
Added by Mchl:
Alternative, IMHO a bit clearer, but it's matter of opinion mostly
$result = array();
foreach($id as $key => $value) {
$result[] = array('id' => $id[$key], 'qty' => $qty[$key]);
}
Also one-liner w/ lambda (PHP >= 5.3.0) and short array syntax [] (PHP >= 5.4)
$combined = array_map(function($id, $qty) {return ['id' => $id, 'qty' => $qty];}, $id, $qty);
or callback and old array() for earlier versions
function comb($id, $qty)
{
return array('id' => $id, 'qty' => $qty);
}
$combined = array_map('comb', $id, $qty);

Categories