如何从数组的所有索引中获取特定值

时间:2019-05-11 13:43:35

标签: php arrays wordpress wordpress-theming polylang

我有一个要迭代的数组,以将项目推入选择框,但是我不知道该怎么做。

我从函数中获得的数组:

array(2) { 
    ["de"]=> array(10) { 
        ["id"]=> int(10) 
        ["order"]=> int(1) 
        ["slug"]=> string(2) "de" 
        ["locale"]=> string(5) "de-DE" 
        ["name"]=> string(7) "Deutsch" 
        ["url"]=> string(34) "http://localhost/werk/Mol/de/haus/" 
        ["flag"]=> string(66) "http://localhost/werk/Mol/wp-content/plugins/polylang/flags/de.png" 
        ["current_lang"]=> bool(false) 
        ["no_translation"]=> bool(false) 
        ["classes"]=> array(4) { 
            [0]=> string(9) "lang-item" 
            [1]=> string(12) "lang-item-10" 
            [2]=> string(12) "lang-item-de" 
            [3]=> string(15) "lang-item-first" 
            } 
        } 
    ["nl"]=> array(10) { 
        ["id"]=> int(3) 
        ["order"]=> int(2) 
        ["slug"]=> string(2) "nl" 
        ["locale"]=> string(5) "nl-NL" 
        ["name"]=> string(10) "Nederlands" 
        ["url"]=> string(26) "http://localhost/werk/Mol/" 
        ["flag"]=> string(66) "http://localhost/werk/Mol/wp-content/plugins/polylang/flags/nl.png" 
        ["current_lang"]=> bool(true) 
        ["no_translation"]=> bool(false) 
        ["classes"]=> array(4) { 
            [0]=> string(9) "lang-item" 
            [1]=> string(11) "lang-item-3" 
            [2]=> string(12) "lang-item-nl" 
            [3]=> string(12) "current-lang" 
            } 
        } 
} 

我尝试了一个foreach方法,但是我只得到了数组的索引

<?php 
$translations = pll_the_languages(array('raw' => 1));

$lang_codes = array();

foreach ($translations as $key => $value) {
  array_push($lang_codes, $key);
}

?>

我需要此数组中所有索引(de&nl)的语言段,URL和标志,我该怎么办?

2 个答案:

答案 0 :(得分:2)

在外部数组上进行一次简单的迭代,然后从子数组中选择所需的值。

<?php 
$translations = pll_the_languages(array('raw' => 1));

$lang_codes = array();

foreach ($translations as $lang => $info) {

    $lang_codes[$lang] = [  'slug' => $info['slug'],
                            'url' => $info['url'],
                            'flag' => $info['flag']
                        ];
}   
?>

答案 1 :(得分:2)

您可以这样处理

$res = [];
foreach($translations as $key  => $value){
   $res[$key] = [
    'slug' => $value['slug'],
    'url'  => $value['url'],
    'flag' => $value['flag']
   ];
 }

Live Demo

相关问题