【问题标题】:Echo each key value from array if second array key equals如果第二个数组键等于,则从数组中回显每个键值
【发布时间】:2015-07-23 20:50:17
【问题描述】:

我有两个数组:

$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 中的值。我不完全确定从哪里开始。但在示例中,我会回应以下内容,因为它们的 keey 存在于比较中。

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

【问题讨论】:

  • 暴力破解:一个普通的循环......?

标签: php arrays function compare exists


【解决方案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',
)

【讨论】:

  • 太棒了!我走在正确的轨道上,转身使用其他一些 php 函数。谢谢!
【解决方案2】:

这样做

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    • 2021-11-09
    相关资源
    最近更新 更多