Php 比较两个数组中的键和值并存储相同的值
我想将一个数组中的键与另一个数组中的值进行比较,并在匹配时存储第一个数组中的值(其键与第二个数组中的值匹配) 对于我的代码,它总是呼出Php 比较两个数组中的键和值并存储相同的值,php,Php,我想将一个数组中的键与另一个数组中的值进行比较,并在匹配时存储第一个数组中的值(其键与第二个数组中的值匹配) 对于我的代码,它总是呼出4。我怎样才能修改它,使其呼出1234 守则: $first = array('location', 'genre', 'studio', 'Lord_Of_the_Rings'); $second = array( 'location' => 1, 'genre' => 2, 'studio' => 3,
4
。我怎样才能修改它,使其呼出1234
守则:
$first = array('location', 'genre', 'studio', 'Lord_Of_the_Rings');
$second = array(
'location' => 1,
'genre' => 2,
'studio' => 3,
'Lord_Of_the_Rings' => 4
);
while ($el = current($second)) {
$d .= ','.key($second);
next($second);
}
$d = ltrim($d, ',');
$d = explode(',', $d);
foreach ($first as $the_tax) {
foreach ($d as $key => $v) {
if (in_array($v, $first)) {
$t = $second[$v];
}
}
echo $t.'<br>';
}
$first=array('location'、'genre'、'studio'、'Lord_Of the_Rings');
$second=数组(
“位置”=>1,
“流派”=>2,
“工作室”=>3,
“指环王”=>4
);
而($el=当前($second)){
$d.=','.key($second);
其次(第二美元);
}
$d=ltrim($d,,');
$d=爆炸(“,”,$d);
foreach($第一个作为$U税){
foreach($d作为$key=>$v){
if(在_数组中($v,$first)){
$t=$second[$v];
}
}
回声$t.“
”;
}
您应该将echo
语句移动/添加到块中,在块中指定$t
的值,可能是这样:
foreach ($first as $the_tax) {
foreach ($d as $key => $v) {
if (in_array($v, $first)) {
$t = $second[$v];
echo $t.' ';
}
}
echo '<br>';
}
foreach($first作为$u税){
foreach($d作为$key=>$v){
if(在_数组中($v,$first)){
$t=$second[$v];
回声$t.';
}
}
回声“
”;
}
最诚实的说,如果你不解释你的目标,我甚至不理解你的代码在试图做什么。试着这样做:
<?php
$first = array('location', 'genre', 'studio', 'Lord_Of_the_Rings');
$second = array(
'location' => 1,
'genre' => 2,
'studio' => 3,
'Lord_Of_the_Rings' => 4
);
$intersect = array_intersect($first, array_keys($second));
foreach($intersect as $key)
echo $second[$key];
?>
您可以翻转第二个数组中的键,然后选择2的交点。类似这样的东西
<?php
$first = array('location', 'genre', 'studio', 'Lord_Of_the_Rings');
$second = array(
'location' => 1,
'genre' => 2,
'studio' => 3,
'Lord_Of_the_Rings' => 4
);
$flipped = array_flip($second);
print implode(' ',array_keys(array_intersect($flipped, $first)));
?>
您的代码似乎非常复杂。或者您的示例数据过于简单。例如,当array\u键($second)==$first
和array\u值($second)=范围(1,4)
时,为什么需要两个数组?顺便说一句,array\u flip
可能很有用:我在第一句话中说了我想要实现的目标。更详细地说,我正在制作输入框,希望每个输入框都具有第二个数组的值。这个答案实际上符合我的要求,但不幸的是,它在我的代码中并没有像预期的那样工作。我可能不得不重新提出这个问题。