0

我想将某些值保存$_POST到文件中。但我只想要键在数组中的值$lang

举个例子:

$_POST = [1 => "a", 2 => "b", 3 => "c"];
$lang = [2, 3];

有了这个输入,我只想要数组$_POST中键所在位置的值。$lang

预期输出为:

[2 => "b", 3 => "c"]

现在我正在尝试使用ArrayIteratorand归档它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" );   
}

所以我有点卡住了如何解决这个问题?

4

3 回答 3

1

尝试这个 :

// 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" );
}
于 2015-12-17T12:25:05.370 回答
1

由于您希望通过键将两个数组相交,因此您可以使用array_intersect_key(),但由于键是值,$lang因此您只需先将其翻转array_flip(),例如

print_r(array_intersect_key($_POST, array_flip($lang)));
于 2015-12-17T13:13:34.227 回答
-1

两个数组组合请尝试以下代码:-

<?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));
?>

此代码对于两个数组合并和合并很有用

于 2015-12-17T12:31:08.443 回答