PHP - 从数组中的某个索引获取元素,其中一个元素具有特定值

时间:2014-02-24 16:35:47

标签: php arrays

当一个值的值等于指定值时,是否有一种简单的方法可以在数组中获取一组值?
例如,我从数据库中检索此数组,其中包含网站上的活动语言: [$ active_lang]

Array
(
    [0] => Array
        (
            [id] => 1
            [code] => pt
            [idiom] => Português
        )

    [1] => Array
        (
            [id] => 2
            [code] => es
            [idiom] => Espanhol
        )

    [2] => Array
        (
            [id] => 3
            [code] => en
            [idiom] => Inglês
        )

)

然后我获取活动语言的内容: [$ records]

Array
(
    [0] => Array
        (
            [id] => 1
            [page_base_id] => 1
            [language] => pt
            [title] => Title pt
            [subtitle] => Subtitle pt
            [description] => Description pt
        )

    [1] => Array
        (
            [id] => 2
            [page_base_id] => 1
            [language] => es
            [title] => Title es
            [subtitle] => Subtitle es
            [description] => Description es
        )

    [2] => Array
        (
            [id] => 3
            [page_base_id] => 1
            [language] => en
            [title] => Title en
            [subtitle] => Subtitle en
            [description] => Description en
        )

)

我现在需要的是一种在foreach数组内的$active_lang内回显正确内容的方法,并避免进行第二次循环以达到在{{1}内显示的正确语言数组。我目前正在使用此代码:

$records

有没有办法做这样的事情?

<div class="tab-content">
  <?php
  foreach ($active_lang as $lang) { ?>
  <div class="tab-pane" id="tab_<?php echo $lang['code']; ?>">
    <div class="row-fluid ">
      <div class="span12">
        <div class="control-group">
          <div class="controls">
            <label class="control-label">Ttile</label>
            <input id="title_1_pt" type="text" class="span12 " value="
            <?php 
            foreach($records_languages as $record){
              if($record['language']==$lang['code']){
                echo $record['title'];
              }
            }
            ?>
            " />
          </div>
        </div>
      </div>
    </div>
  </div>
  <?php } ?>
</div>

1 个答案:

答案 0 :(得分:1)

您可以在最开始创建新数组:

$records = array();
foreach ($records_languages as $record) {
    $records[$record['language']] = $record;
}

然后使用

$records[$lang['code']]['title']

这样可以省去一些循环。