将通配符应用于assoc的键。排列

时间:2014-04-29 09:33:31

标签: php arrays wildcard

我在这个网站上已经阅读了类似的问题,但仍然无法弄清楚如何将它应用到我的阵列。我有以下内容:

$var = array(
  [docs] = > array (
     [0] => array(
       [title_en] => some_title_en,
       [text_en] => some_text_en
      )
     [1] => array(
       [title_es] => some_title_es,
       [text_es] => some_text_es
      )
     [2] => array(
       [title_de] => some_title_de,
       [text_de] => some_text_de
      ) 
   )
 )

foreach ($var['docs'] as $array) {
   echo 'Title: '.$array['title_?'];
   echo 'Text: '.$array['text_?'];
}

有没有办法输出带有通配符的数组:titletext,如:$array['title_*']$array['text_*']

2 个答案:

答案 0 :(得分:2)

考虑重建Mark Ba​​ker提到的阵列。如果从外部数据源获取数据并不重要:

<?php

$array = array(
    'docs' => array(
        array(
            'title_en' => 'some_title_en',
            'text_en' => 'some_text_en',
        ),
        array(
            'title_es' => 'some_title_es',
            'text_es' => 'some_text_es',
        ),
        array(
            'title_de' => 'some_title_de',
            'text_de' => 'some_text_de',
        ),
    )
);

$newArray = array();

foreach ($array as $category => $texts) {
    $newArray[$category] = array();

    foreach ($texts as $textsLanguage) {
        foreach ($textsLanguage as $key => $value) {
            if (preg_match('/^(.*)_([a-z]{2})$/', $key, $match)) {
                if (!isset($newArray[$category][$match[2]])) {
                    $newArray[$category][$match[2]] = array();
                }

                $newArray[$category][$match[2]][$match[1]] = $value;
            }
        }
    }
}

print_r($newArray);

输出:

Array
(
    [docs] => Array
        (
            [en] => Array
                (
                    [title] => some_title_en
                    [text] => some_text_en
                )

            [es] => Array
                (
                    [title] => some_title_es
                    [text] => some_text_es
                )

            [de] => Array
                (
                    [title] => some_title_de
                    [text] => some_text_de
                )

        )

)

现在你可以简单地使用

$lang = 'en';
var_dump( $newArray['docs'][$lang]['title'] ); //string(13) "some_title_en"

DEMO

答案 1 :(得分:0)

实际上,我最终使用了自己的解决方法:

foreach ($var['docs'] as $array) {
   foreach ($array as $key => $val) {
       if (substr($key,0,5) == 'title' || substr($key,0,4) == 'text') {
          $lang = explode('_', $key);
          $sufx = $lang[1];
       }
   }
   echo 'Title: '.$array['title_'.$sufx];
   echo 'Text: '.$array['text_'.$sufx];
}