如何通过键获取两个数组的交集?
How to get the intersection of two arrays by keys?
我想将 $_POST
中的某些值保存到文件中。但我只想要键在数组 $lang
.
中的值
举个例子:
$_POST = [1 => "a", 2 => "b", 3 => "c"];
$lang = [2, 3];
有了这个输入,我只需要来自 $_POST
的值,其中键在 $lang
数组中。
预期输出为:
[2 => "b", 3 => "c"]
现在我正在尝试使用 ArrayIterator
和 MultipleIterator
将其存档,但这会循环遍历两个数组:
$post = new ArrayIterator($_POST);
$lang_array = new ArrayIterator($lang);
$it = new MultipleIterator;
$it->attachIterator($post);
$it->attachIterator($lang_array);
$fh = fopen('name.php', 'w');
foreach($it as $e) {
fwrite($fh , $e[1] .'-' . $e[0] );
fwrite($fh ,"\n" );
}
所以我有点卡住了如何解决这个问题?
试试这个:
// Combining both arrays into one.
$combined_array = array_merge($_POST, $lang);
$fh = fopen('name.php', 'w');
foreach($combined_array as $key => $value){
fwrite($fh , $key .'-' . $value );
fwrite($fh ,"\n" );
}
两个数组合并请试试这个代码:-
<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);
print_r($c);
?>
和两个数组合并:-
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
这段代码对于两个数组的组合和合并很有用
因为你想通过键对两个数组进行交集,你可以使用array_intersect_key()
, but since the keys are values in $lang
you just have to flip it first with array_flip()
,例如
print_r(array_intersect_key($_POST, array_flip($lang)));
我想将 $_POST
中的某些值保存到文件中。但我只想要键在数组 $lang
.
举个例子:
$_POST = [1 => "a", 2 => "b", 3 => "c"];
$lang = [2, 3];
有了这个输入,我只需要来自 $_POST
的值,其中键在 $lang
数组中。
预期输出为:
[2 => "b", 3 => "c"]
现在我正在尝试使用 ArrayIterator
和 MultipleIterator
将其存档,但这会循环遍历两个数组:
$post = new ArrayIterator($_POST);
$lang_array = new ArrayIterator($lang);
$it = new MultipleIterator;
$it->attachIterator($post);
$it->attachIterator($lang_array);
$fh = fopen('name.php', 'w');
foreach($it as $e) {
fwrite($fh , $e[1] .'-' . $e[0] );
fwrite($fh ,"\n" );
}
所以我有点卡住了如何解决这个问题?
试试这个:
// Combining both arrays into one.
$combined_array = array_merge($_POST, $lang);
$fh = fopen('name.php', 'w');
foreach($combined_array as $key => $value){
fwrite($fh , $key .'-' . $value );
fwrite($fh ,"\n" );
}
两个数组合并请试试这个代码:-
<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);
print_r($c);
?>
和两个数组合并:-
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
这段代码对于两个数组的组合和合并很有用
因为你想通过键对两个数组进行交集,你可以使用array_intersect_key()
, but since the keys are values in $lang
you just have to flip it first with array_flip()
,例如
print_r(array_intersect_key($_POST, array_flip($lang)));