Is there a way to do the following:
$array1 = array( "two" => "2", "three" => "3")
$array2 = array("two", "three", "four")
I want to match array2's value with array1's key. Upon matching, I want to output array1's value.
Thank you
Like Mark Baker commented, you can use array_flip() together with array_intersect_key()
$array1 = array( "two" => "2", "three" => "3");
$array2 = array("two", "three", "four");
$array2 = array_flip($array2);
print_r(array_intersect_key($array1, $array2) );
Output:
Array
(
[two] => 2
[three] => 3
)
$array1 = array( "two" => "2", "three" => "3");
foreach($array1 as $key=>$val){
$array_1[] = $key;
}
$array2 = array("two", "three", "four");
$result = array_diff($array2, $array_1);
print_r($result);
Related
I have 2 arrays:
$array1 = ["b" => "no", "c" => "no", "d" => ["y" => "no"]];
$array2 = ["a" => "yes", "b" => "yes", "c" => "yes", "d" => ["x" => "yes", "y" => "yes", "z" => "yes"]];
I want to return the members of $array2 whose keys are also present in $array1.
Desired output:
$array3 = ["b" => "yes", "c" => "yes", "d" => ["y" => "yes"]];
Basically I need the same functionality as array_intersect_key but I want to keep the values from $array2 instead of $array1.
Does such a function exist? Also needs to recurse into child arrays. Thanks!
*Edit*
As Andri suggested in his comment, I attempted to flip the arguments around array_intersect_key($array2, $array1) but in that case what I actually get is:
$array3 = ["b" => "yes", "c" => "yes", "d" => ["x" => "yes", "y" => "yes", "z" => "yes"]];
ie all the children of "d" just because "d" is mentioned in $array1.
There isn't as far as I'm aware a built in function, a method using recursion to process all layers should be easy enough...
$array1 = ["b" => "no", "c" => "no", "d" => ["y" => "no"]];
$array2 = ["a" => "yes", "b" => "yes", "c" => "yes", "d" => ["x" => "yes", "y" => "yes", "z" => "yes"]];
function intersect_key_2 ( array $a1, array $a2 ) {
foreach ( $a1 as $key1 => $value1) {
// If there is a matching element
if ( isset($a2[$key1]) ) {
// Update - if an array, use recursive call else just replace
$a1[$key1] = ( is_array($value1) ) ? intersect_key_2 ( $value1, $a2[$key1])
: $a2[$key1];
}
}
return $a1;
}
print_r(intersect_key_2($array1, $array2));
gives
Array
(
[b] => yes
[c] => yes
[d] => Array
(
[y] => yes
)
)
Ended up writing my own:
function array_intersect_key_values_2($array1, $array2) : array {
$intersection = [];
foreach ($array1 as $key => $value) {
if(isset($array2[$key]))
{
if(is_array($array1[$key]) && is_array($array2[$key]))
{
$intersection[$key] = array_intersect_key_values_2($array1[$key], $array2[$key]);
}
else
{
$intersection[$key] = $array2[$key];
}
}
}
return($intersection);
}
This question already has an answer here:
Convert value from specific multidimensional array key into key in new array with original arrays as value
(1 answer)
Closed 5 months ago.
What's the easiest way to convert
$a = array(
array("id" => 1, "name" => "a1"),
array("id" => 2, "name" => "a2")
);
to
$b = array(
"a1" => array("id" => 1, "name" => "a1"),
"a2" => array("id" => 2, "name" => "a2")
);
I was expecting PHP have some functional programming facilities to do something like:
$b = map($a, function($item) {
return $item["name"];
});
But I didn't find one.
You can use PHP array_column() function. For your use case, the second argument should be null to return the full array.
$a = array(
array("id" => 1, "name" => "a1"),
array("id" => 2, "name" => "a2")
);
$b = array_column($a, null, 'name');
and print_r($b) will result in
Array
(
[a1] => Array
(
[id] => 1
[name] => a1
)
[a2] => Array
(
[id] => 2
[name] => a2
)
)
The only solution I see is to loop through the array and create a new array manually.
For example, like this:
$new_array = [];
foreach ($array as $value)
$new_array[$value['name']] = $value;
You can simply do this
$input = [
["id" => 1, "name" => "a1"],
["id" => 2, "name" => "a2"]
];
$result = array_merge(
...array_map(
fn($item) => [$item['name'] => $item],
$input
)
);
Poor me need to implement this in PHP 5.2, and I do not want to use for loop
here's my implementation:
function getField($x) { return $x['name']; }
$ids = array_map('getField', $result);
$result = array_combine($ids, $result);
See if maybe this helps anybody lol
The accepted answer is close, but "close" only counts with hand grenades.
($unique is an indexed array)
$sub_key = 'country';
$new_array = [];
foreach ($unique as $value) {
$new_array[] = [$sub_key => $value];
}
How about:
$a = array(
array('a' => 'a0', 'b' => 'b0', 'c' => 'c0'),
array('a' => 'a1', 'b' => 'b1', 'c' => 'c1'),
array('a' => 'a2', 'b' => 'b2', 'c' => 'c2'),
);
print_r($a);
print_r(array_combine(array_column($a, 'a'), $a));
Where 'a' is the column to use as the associative index.
This leaves the column that becomes the index in the array.
array_column (PHP 5 >= 5.5.0, PHP 7)
array_combine (PHP 5, PHP 7)
Need to compare two arrays
Working example
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
Array1 Output:
Array ( [a] => green [0] => red [1] => blue )
When I do Like this
$array1 = array();
while($fetch = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$array1[] = $fetch['color'];
}
I get this output:
Array ([0] => gren [1] => red [2] blue
How do I add the "a" to the array and make the first color be number zero?
This adding the "a" but it gets the zero number
array_unshift($array1,"a");
LIKE
Array ( [0] => a [1] => green
I want this
Array ( [a] => green [0]
I'm not sure why you want to do this, but here's how:
$array1 = array();
while ($fetch = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
if (empty($array1)) {
$array1['a'] = $fetch['color'];
} else {
$array1[] = $fetch['color'];
}
}
$arr = array(0 => 'green', 1 => 'red', 2 => 'blue');
$res = array_merge(array('a' => current($arr)), array_slice($arr, 1));
You can do with array_merge and array_shift function:
$arr = array(0 => 'green', 1 => 'red', 2 => 'blue');
$new = array_merge(array('a' => array_shift($arr)), $arr);
Demo: http://codepad.org/osifrZKZ
I have two arrays like this
$array1 = ['name'=>'john', 'age'=> 10]
$array2 = ['name' => 'johnKaff', 'class' => 'User', 'option'=array('c1', 'c2')]
The result i want is
$array2 = ['name' => 'john', 'class' => 'User', 'option'=array('c1', 'c2'), 'age'=> 10]
The values from $array1 should always override if have same key in $array2
Use array_replace():
$result = array_replace($array2, $array1);
Where:
$array1 - The array in which elements are replaced.
$array2 - The array from which elements will be extracted.
Output:
Array
(
[name] => john
[class] => User
[option] => Array
(
[0] => c1
[1] => c2
)
[age] => 10
)
Use the + operator:
$combined_array = $array1 + $array2;
The array listed first wins when each array has an element with the same key.
Example:
$array1 = array('name'=>'john', 'age'=> 10);
$array2 = array('name' => 'johnKaff', 'class' => 'User', 'option'=>array('c1', 'c2'));
$combined_array = $array1 + $array2;
var_dump($combined_array);
Output:
array(4) {
["name"]=>
string(4) "john"
["age"]=>
int(10)
["class"]=>
string(4) "User"
["option"]=>
array(2) {
[0]=>
string(2) "c1"
[1]=>
string(2) "c2"
}
}
You should use array_merge:
array_merge($array1, $array2);
Example:
$arr1 = array('a' => "1", 'b' => "2", 'c' => "3", 'z' => "4");
$arr2 = array('a' => "9", 'b' => "8", 'c' => "7", 'd' => "6", 'e' => "5");
Output:
$result = array(
'a' => array( 'f1' => "1", 'f2' => "9"),
'b' => array( 'f1' => "2", 'f2' => "8"),
'c' => array( 'f1' => "3", 'f2' => "7"),
'd' => array( 'f1' => "0", 'f2' => "6"),
'e' => array( 'f1' => "0", 'f2' => "5"),
'z' => array( 'f1' => "4", 'f2' => "0"),
);
The size of $arr1 can be '>', '<' or '=' size of $arr2
I think this it,
$arr1 = array('a' => "1", 'b' => "2", 'c' => "3", 'z' => "4");
$arr2 = array('a' => "9", 'b' => "8", 'c' => "7", 'd' => "6", 'e' => "5");
foreach($arr1 as $key => $value){
$a[$key]['f1'] = $value;
}
foreach($arr2 as $key => $value){
$b[$key]['f2'] = $value;
}
$c = array_merge_recursive($a, $b);
foreach($c as $key => $value){
$result[$key]['f1'] = (array_key_exists('f1', $value)) ? $value['f1']: 0;
$result[$key]['f2'] = (array_key_exists('f2', $value)) ? $value['f2']: 0;
}
echo "<pre>".print_r ($result, true);
the output:
Array
(
[a] => Array
(
[f1] => 1
[f2] => 9
)
[b] => Array
(
[f1] => 2
[f2] => 8
)
[c] => Array
(
[f1] => 3
[f2] => 7
)
[z] => Array
(
[f1] => 4
[f2] => 0
)
[d] => Array
(
[f1] => 0
[f2] => 6
)
[e] => Array
(
[f1] => 0
[f2] => 5
)
)
array_merge_recursive() should work: http://php.net/manual/en/function.array-merge-recursive.php
otherwise it's simple enough wo implement in a few lines: (Unless you really need the "fn" indices.)
function my_merge(){
$result = array();
foreach(func_get_args() as $a)
foreach($a as $index => $value)
$result[$index][] = $value;
}
Try this:
$keys = array_unique(array_merge(array_keys($arr1), array_keys($arr2)));
$values = array_map(function($key) use ($arr1, $arr2) {
return array('f1' => isset($arr1[$key]) ? $arr1[$key] : "0",
'f2' => isset($arr2[$key]) ? $arr2[$key] : "0"); }
, $keys);
$result = array_combine($keys, $values);
var_dump($result);
Some explanation:
At first get an array $keys of all unique keys of both arrays.
Then for each key the corresponding array of values is then generated.
At last the array of keys and the array of values are combined.
But this does currently only work with two arrays.
Edit Here’s one that works with an arbitrary number of arrays:
$arrays = array($arr1, $arr2);
$keys = array_unique(call_user_func_array('array_merge', array_map('array_keys', $arrays)));
$values = array_map(function($key) use ($arrays) {
return array_combine(array_map(function($key) {
return 'f'.($key+1);
}, array_keys($arrays)),
array_map(function($array) use ($key) {
return isset($array[$key]) ? $array[$key] : "0";
}, $arrays));
}, $keys);
$result = array_combine($keys, $values);
var_dump($result);
Some explanation:
Put all arrays in an array $arrays.
For each array in $arrays, call array_keys on it to get the keys, merge these arrays and get an array $keys of all unique keys.
For each key in $keys, check if the key exists in the array of arrays $arrays.
Combine the keys and values.
$arr1 = array('a' => "1", 'b' => "2", 'c' => "3", 'z' => "4");
$arr2 = array('a' => "9", 'b' => "8", 'c' => "7", 'd' => "6", 'e' => "5");
function combineArray($arr1, $arr2) {
if (is_array($arr1) && is_array($arr2)) {
$rArr = array();
$steps = max ( count($arr1),count($arr2));
$ak1 = array_keys($arr1);
$ak2 = array_keys($arr2);
for ($i=0;$i<$steps;$i++) {
if (!isset($rArr[$i])) $rArr[$i]=array();
$rArr[$i]['f1'] = (isset($arr1[$ak1[$i]])) ? $arr1[$ak1[$i]]: '0';
$rArr[$i]['f2'] = (isset($arr2[$ak2[$i]])) ? $arr2[$ak2[$i]]: '0';
}
return $rArr;
}else {
return false;
}
}
echo "<pre>".print_r (combineArray($arr1, $arr2),true);
might work :)
Run through the first array, store the f1 values from the array and set the default 0 for all f2 values.
Run through the second array, store the f2 values from the array and only set the default 0 for the respective f1 value if it is not already declared.
Use ksort() if desired to alphabetize the first level keys.
Code: (Demo)
$array1 = ['a' => "1", 'b' => "2", 'c' => "3", 'z' => "4"];
$array2 = ['a' => "9", 'b' => "8", 'c' => "7", 'd' => "6", 'e' => "5"];
$result = [];
foreach ($array1 as $k => $v) {
$result[$k] = ['f1' => $v, 'f2' => "0"];
}
foreach ($array2 as $k => $v) {
$result[$k] = ['f1' => $result[$k]['f1'] ?? "0", 'f2' => $v];
}
var_export($result);