Search code examples
phparrayswordpresswordpress-themingpolylang

How to get specific values out of all indexes in an array


I have an array which I want to iterate over to push the items into a select box, but I can't figure out how to do it.

The array I get from the function:

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" 
            } 
        } 
} 

I tried a foreach but I did only get the indexes of the array

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

$lang_codes = array();

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

?>

I need the language slug, URL, and flag from all indexes in this array (de & nl), what should I do?


Solution

  • A simple iteration over the outer array and then pick the values you want from the sub array.

    <?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']
                            ];
    }   
    ?>