如果第二个数组键等于,则从数组中回显每个键值

时间:2015-05-12 19:42:38

标签: php arrays function compare exists

我有两个数组:

$choices = array  (
        [model] => 3D Modeling / BIM
        [edb] => Engineering & Design-Build
        [gse] => Green & Sustainable Energy
        [ipd] => Integrated Project Design
        [lc] => Lean Construction
        [mt] => Material Supply
        [ecs] => Electrical Construction & Service
        [fps] => Fire Protection Services
        [hms] => HVAC & Mechanical Service
        [tsl] => Traffic Signal & Lighting
    )
$servicesSelected = array (
        [model] => 0
        [ipd] => 1
        [lc] => 2
        [mt] => 3
    )

我试图检查是否有任何数组2键等于数组1键,如果该键等于数组2键,则打印数组1中的值。我不完全确定从哪里开始。但在这个例子中,我会回应以下内容,因为它们的关键存在于比较中。

  • 3D模型/ BIM
  • 综合项目设计
  • 精益建设
  • 物料供应

2 个答案:

答案 0 :(得分:1)

这应该这样做:

<?php
header('Content-Type:text/plain');
$choices = array  (
'model' => ' 3D Modeling / BIM',
'edb' => ' Engineering & Design-Build',
'gse' => ' Green & Sustainable Energy',
'ipd' => ' Integrated Project Design',
'lc' => ' Lean Construction',
'mt' => ' Material Supply',
'ecs' => ' Electrical Construction & Service',
'fps' => ' Fire Protection Services',
'hms' => ' HVAC & Mechanical Service',
'tsl' => ' Traffic Signal & Lighting');
$servicesSelected = array (
'model' => 0,
'ipd' => 1,
'lc' => 2,
'mt' => 3);

$printArray = array_intersect_key($choices , $servicesSelected );

var_export($printArray);
?>

结果

array (
  'model' => ' 3D Modeling / BIM',
  'ipd' => ' Integrated Project Design',
  'lc' => ' Lean Construction',
  'mt' => ' Material Supply',
)

答案 1 :(得分:1)

这样做

foreach($servicesSelected as $key2=>$serviceSelected)
  foreach($choices as $key1=>$choice)
    if($key1==$key2) echo $choice;
相关问题